当前位置: 首页 > 知识库问答 >
问题:

Hibernate方法验证并不总是有效

丁翊歌
2023-03-14
@Validated
@SpringBootApplication
public class Application {
public static void main(String[] args) {
   SpringApplication.run(Application.class, args);
   someService.doStuff(new Item(null);  // WHY NOT THROWN????????!!!!!! 
   // Expecting ConstraintViolationException: doStuff.item.content: must not be null
}}
// ----------------------

public class Item {
    @NotNull
    String content;  // to be validated
   //constructor, getter, setter
}

@Validated
@Service
public class SomeService {
    void doStuff(@Valid Item item) {} // should break for Item's content = null
}
  1. ConstraintViolationException在将无效调用放入控制器的contructor时引发:
public SomeController(SomeService someService){
    this.someService = someService;
    someService.doStuff(new Item(null); // throws ConstraintViolationException  
}
@GetMapping("item")
public String item() {
    someService.doStuff(new Item(null); // throws ConstraintViolationException
    return "You never get here.";
}

共有1个答案

应嘉容
2023-03-14

我不知道如何在应用程序中获得SomeService实例,但是下面的代码对我来说很有效(每个类都在不同的文件中):

@AllArgsConstructor
@Getter
@Setter
public class Item {

  @NotNull
  String content;
}



@Validated
@Service
public class SomeService {

  public void doStuff(@Valid Item item) {
    System.out.println(format("Item.content = %s", item.getContent()));
  }
}



@SpringBootApplication
public class TestingPurposeApplication {

  public static void main(String[] args) {
    ConfigurableApplicationContext context = SpringApplication.run(TestingPurposeApplication.class, args);
    SomeService someService = context.getBean(SomeService.class);
    someService.doStuff(new Item(null));
  }
}

结果:

使用:

ConfigurableApplicationContext context = SpringApplication.run(MyApplication.class, args);
MyClass myInstance = context.getBean(MyClass.class);
 类似资料:
  • 我使用OpenSSL(在C中)对文本进行签名,但是我的Java程序并不总是验证签名的消息(只有大约1/5得到验证)。有趣的是,https://kjur.github.io/jsrsasign/sample/sample-ecdsa.html没有证实其中任何一个: 曲线名称:secp256k1签名算法:SHA256with ECDSA 私钥 密钥 失败: 成功: 爪哇 C.

  • 我知道这在这个论坛上不是新问题,但我很困惑我该怎么做。 问题:我正在用spring mvc+Hibernate开发一个应用程序。对于服务器端验证,我在controller中使用@valid注释,在bean中使用@null和@notnull注释。 例如: 这个验证很好地进行,数据也保存在DB中。 但我想验证唯一约束,引用完整性和其他约束使用注释没有任何验证器类。 有可能吗?如果没有,那么什么是最好和

  • 我需要应用一个双值验证,这需要与圆周率匹配。我正在考虑使用@pattern(regex=“3.14159265359”)。这是使用Hibernate验证约束应用这样一个约束的最佳方式吗?谢谢

  • 问题内容: 我需要进行以下测试,以验证是否已调用Person类的所有getter。到目前为止,我已经使用了Mockito的verify()来确保每个getter都被调用。有没有办法通过反思做到这一点?可能是将新的吸气剂添加到Person类的情况,但是测试会错过这一点。 问题答案: 通常,不要嘲笑被测类。如果您的测试是针对Person的,则您永远都不会看到它,因为这很明显地表明您正在测试模拟框架而不

  • 我现在把这两者搞混了。我知道Hibernate Validator6是Bean验证2.0规范的参考实现。它支持分组、错误消息国际化、自定义方法验证等。问题是Spring5支持这些特性还是我只剩下Hibernate Validator6了? 网上所有的参考例子都建议使用Hibernate验证器,没有什么关于Spring验证的发现,请建议或指向其他链接。