我在使用 Spring AOP 时遇到了这个奇怪的问题,我希望有人能对此有所启发。
我正在使用 CGLIB 代理,当我执行以下方面时,我得到一个空指针:
@Aspect
@Component //i.e. Singleton
public class MyAspect {
private static final Logger logger = LoggerFactory.getLogger(MyAspect.class);
{
logger.debug("new instance of MyAspect"); //Line 1
}
private AutowireCapableBeanFactory factory;
@Inject
public MyAspect(AutowireCapableBeanFactory factory) {
if (factory ==null) {
logger.debug("your factory is null"); //Line 2
} else {
logger.debug("your factory is not null");
}
this.factory = factory;
}
@AfterReturning(pointcut = "@annotation(com.domain.annotations.MyAnnotation)")
public void doSomething() {
if (factory ==null) {
logger.debug("your factory is null again"); //Line 3
}
// this is a request scoped bean
MyRequest request = factory.getBean(MyRequest.class); //Line 4
if (request != null) {
logger.debug("No");
}
else {
logger.debug("Yes");
}
}
}
我在第 4 行收到 NullPointerException。我可以看到“工厂”在第 3 行为空,但在第 2 行创建实例时它不为空。我还在跟踪第 1 行创建的实例.
此设计使用接口(interface)(JDK 动态代理)。为什么我的实例变量在运行时变为 null,是否有解决方法?
最佳答案
总而言之,您不能将 Spring 的基于构造函数的注入(inject)与 Aspects 一起使用。关于这个主题有一个很好的论坛讨论 here .
我个人按照上述论坛中的建议对我的方面使用基于属性的注入(inject)。下面的示例允许您将服务注入(inject)审计方面。您不需要任何额外的 XML 配置,只要您使方面实现 ApplicationContextAware。
@Aspect
@Component("auditAspect")
public class AuditAspect implements ApplicationContextAware {
ApplicationContext context;
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
// do stuff with context here
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
关于java - 注入(inject)的实例变量在方面执行时为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6351559/