休眠方法验证并非始终有效 [英] Hibernate method validation NOT always working

查看:50
本文介绍了休眠方法验证并非始终有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要进行Hibernate的验证- ConstraintViolationException-不会在带有spring-boot-starter-web的SpringBoot应用程序(SpringBoot的最新版本)的main()中抛出:

Why is Hibernate's validation - ConstraintViolationException - NOT thrown in main() of a SpringBoot app (SpringBoot's latest version) with spring-boot-starter-web:

@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
}

奇怪的是,在其他情况下,对于相同的方法调用,Hibernate验证可以按预期运行:

    当我将无效的调用放入控制器的构造器时,会抛出
  1. ConstraintViolationException:
  1. ConstraintViolationException is thrown when I put the invalid call in a controller's contructor:

public SomeController(SomeService someService){
    this.someService = someService;
    someService.doStuff(new Item(null); // throws ConstraintViolationException  
}

  1. 也正如预期的那样,当我将无效调用 in a constructor method 并在测试或邮递员中调用端点时,会引发ConstraintViolationException

@GetMapping("item")
public String item() {
    someService.doStuff(new Item(null); // throws ConstraintViolationException
    return "You never get here.";
}

推荐答案

不确定如何在Application中获得someService实例,但是以下代码对我有用(每个类在不同文件中):

Not sure how are you getting someService instance in Application, but the following code works for me (every class in a different file):

@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);

是通过main方法获取由Spring管理的组件的合适方法.

Is the suitable way to get a component managed by Spring in main method.

这篇关于休眠方法验证并非始终有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆