I have a strange issue that I cant resolve or find the answer to.
I've defined my own validator:
@Component
public class SingleInstanceValidator implements ConstraintValidator<SingleInstanceRule, Plan> {
@Autowired(required = true)
private UserService userService;
...
}
Without the @Valid annotation I cant get the injection to work and instead need to inject like this.
@Component
public class SingleInstanceValidator implements ConstraintValidator<SingleInstanceRule, Plan> {
@Autowired(required = true)
private UserService userService;
@Override
public void initialize(SingleInstanceRule singleInstanceRule) {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
...
}
This worked to make it inject the UserService. However, with this solution I could not get @ExceptionHandler to work and the injection would also fail in our tests.
With @Valid I can make both the injection and @ExceptionHandler to function properly (catching BindException.class)
However... and this is the issue I dont get. I cannot use @RequestBody together with @Valid, the @Autowired doesnt work then, and the @ExceptionHandler wont work.
So before we had this:
@RequestMapping(method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public Plan create(@RequestBody final Plan entity) throws Exception {
...
}
and now I want this:
... (same annotations before)
public Plan create(@Valid @RequestBody final Plan entity) throws Exception {
...
}
But this will fail. I tried and figured this would work and it did
... (same annotations before)
public Plan create(@Valid Plan entity) throws Exception {
...
}
But we need to have the @RequestBody annotation, otherwise some relations are lost of the Plan entity.
Does anyone have any idea how we could achieve using both @Valid and @RequestBody and still be able to autowire the custom validator and handle exceptions using the @ExceptionHandler annotation?