不会注入具有@Autowired依赖项的@ControllerAdvice [英] @ControllerAdvice with @Autowired dependency not being injected
问题描述
任何人都知道如何向@ControllerAdvice注入依赖项吗?
Anyone knows how to inject a dependency to a @ControllerAdvice?
我的@ControllerAdvice扩展了Spring的ResponseEntityExceptionHandler,并且不实现任何接口。
My @ControllerAdvice extends Spring's ResponseEntityExceptionHandler and implements no interfaces.
已正确调用@ControllerAdvice,但从未注入@Autowired依赖项。
The @ControllerAdvice gets called correctly, but the @Autowired dependency is never injected. There are no startup injection errors, the dependency is simply null.
我想这与Spring如何使用cglib代理@ControllerAdvice有关,以便获得@Autowired批注
I guess it has to do with how Spring proxies the @ControllerAdvice with cglib so that the @Autowired annotation gets lost.
我通过实现一个接口进行了测试,以便Spring可以创建一个JDK代理,但它也不起作用。实际上,即使使用接口也没有调用它,即使我也使用@ControllerAdvice注释了该接口。
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.
有没有一种方法可以指定该接口对于这种特殊情况,Spring应该使用JDK代理吗?
Is there a way to specify that Spring should use JDK proxies for that particular case?
编辑:顺便说一下,我正在使用Spring 3.2.4.RELEASE。
I'm using Spring 3.2.4.RELEASE, by the way.
示例类:
@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!
}
}
推荐答案
在您的情况下,您的bean位于CGLIB代理之后。
它创建您的bean的子类,并且由于该方法具有 final
修饰符,因此它无法更改原始 ResponseEntityExceptionHandler
类以插入对后面的bean的调用-请检查关于CGLIB的其他答案。
In your case your bean is behind a CGLIB proxy.
It creates a subclass of your bean and as the method has final
modifier it can't change the behavior of the original ResponseEntityExceptionHandler
class to insert a call to the bean behind - please check my other answer about CGLIB.
CGLIB代理是另一个将方法调用委派给原始bean的对象。
CGLIB proxy is a different object that delegates the method calls to the original bean.
请注意,仅通过子类(即没有对象的分离)就不可能实现大部分Spring功能。当单个作用域
bean引用一个会话作用域
bean时,它将如何工作-显然有许多 session-scope
bean和仅一个 Singleton-scoped
bean。
Please note that it would not be possible to implement much of Spring functionality only with subclassing i.e. without this separation of objects. How would it work when singleton-scoped
bean references a session-scoped
bean - obviously there are many session-scope
beans and only one singleton-scoped
bean.
这篇关于不会注入具有@Autowired依赖项的@ControllerAdvice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!