0

For example:

public class MyBean {

    @MyValidationAnnotation
    private String whatever;

    ...

}

@Component
public class MyConstraintValidator
        implements ConstraintValidator<MyValidationAnnotation, String> {

    @Autowired
    private SomeSpringBean whatever;

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        ...
        whatever.doSomething()
        ...
    }

    ...

}

Using it in a controller like this works fine:

@Controller
public class MyController {

    @RequestMapping(...)
    public String whatever(@RequestBody @Validated MyBean bean) {
        ...
    }

}

But in the data access layer it throws NPE:

@Autowired
private MyBeanRepository repository;

...

MyBean bean = ...
repository.save(bean); // throws NPE at whatever.doSomething()

That is because MyConstraintValidator instance was outside of the Spring's container in the second place.

So how to implement and/or configure a validator working well both in a controller and in the data access layer? (I'm using Hibernate + Spring Data JPA for it)

Viktor
  • 1,298
  • 15
  • 28
  • 2
    By correctly configuring your JPA EntityManager to use the same validator factory. – M. Deinum Sep 09 '16 at 14:04
  • Have a look at this question: http://stackoverflow.com/questions/2712345/jsr-303-dependency-injection-and-hibernate – Ralph Sep 09 '16 at 14:24

0 Answers0