Anyone knows how to inject a dependency to a @ControllerAdvice?
My @ControllerAdvice extends Spring's ResponseEntityExceptionHandler and implements no interfaces.
The @ControllerAdvice gets called correctly, but the @Autowired dependency is never injected. There are no startup injection errors, the dependency is simply null.
I guess it has to do with how Spring proxies the @ControllerAdvice with cglib so that the @Autowired annotation gets lost.
I tested by implementing an interface, so that Spring could create a JDK proxy but it didn't work either. Actually with an interface, it didn't even gets called at all... even if I also annotate the interface with @ControllerAdvice.
Is there a way to specify that Spring should use JDK proxies for that particular case?
EDIT: I'm using Spring 3.2.4.RELEASE, by the way.
Sample class:
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
@Autowired(required = true)
public AuditService auditService;
@ExceptionHandler(value = { RuntimeException.class })
public final ResponseEntity<Object> handleRuntimeException(Exception ex, WebRequest request) {
// auditService is null here!
}
}
final
? Are you sure that you're checking the state of the right object in the right time - CGLIB proxy is still a different instance which fields are null -it just delegates the calls to the bean behind, because of that methods can't be made final. – Boris Treukhov