How to autowire service in ConstraintValidator

社会主义新天地 提交于 2019-12-01 20:56:28

Don't you have a Validator configured in your bean context. If you are bootstrapping Validator via Validation.buildDefaultValidatorFactory(); you are bypassing the Spring mechanism and you get a Validator which is not aware of Spring beans and components. Hence injection is not working. In your test you want to get hold of the Spring provided Validator.

If your main code is working, then it should be straight forward to get your test working. You need to use @ContextConfiguration on your test class, see this for more details: http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/testing.html

In general, there are 2 ways to test this:

  • unit test
  • integration test

For unit test, you need to create an instance of the UniqueEmailValidator and set a UserService on that instance (normally a mock UserServer).

For integration test, you need to have the spring context initialized as I mentioned above.

You can call injection all @Autowired service:

@Override
public void initialize(UniqueEmail uniqueEmail) {
   org.springframework.web.context.support.SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!