0

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?

davidjons
  • 135
  • 8
  • When you say 'But this will fail' what exactly are you seeing in the stacktrace? Also, on what version of Spring are you on? May be this could help: http://stackoverflow.com/q/6129285/2231632 ? – Praba Sep 08 '14 at 12:59
  • I get `NullpointerException` since the `@Autowired` annotation does not work. So, if I just remove the `@RequestBody`, the `@Autowired` works. However, we need `@RequestBody`. We are using Spring 3.2.2.RELEASE – davidjons Sep 09 '14 at 06:46

0 Answers0