@Aspect 方面的 Spring 自动装配 bean 为空 [英] Spring autowired bean for @Aspect aspect is null

查看:86
本文介绍了@Aspect 方面的 Spring 自动装配 bean 为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下弹簧配置:

<context:component-scan base-package="uk.co.mysite.googlecontactsync.aop"/>

<bean name="simpleEmailSender" class="uk.co.mysite.util.email.simple.SimpleEmailSenderImplementation"/>

<aop:aspectj-autoproxy/>

然后我有一个方面:

@Aspect
public class SyncLoggingAspect {
    @Autowired
    private SimpleEmailSender simpleEmailSender

    @AfterReturning(value="execution(* uk.co.mysite.datasync.polling.Poller+.doPoll())", returning="pusher")
    public void afterPoll(Pusher pusher) {      
        simpleEmailSender.send(new PusherEmail(pusher));
    }
}

这方面有效(我可以在 afterPoll 上遇到断点)但 simpleEmailSender 为空.不幸的是,我找不到关于为什么会这样的明确文档.(作为记录,我的 simpleEmailSender bean 存在并正确连接到其他类)以下事情让我感到困惑:

This aspect works (I can hit a breakpoint on afterPoll) but simpleEmailSender is null. Unfortunately I cannot find clear documentation on why this is. (For the record, my simpleEmailSender bean exists and is correctly wired into other classes) The following things confuse me:

  1. context:component-scan 是否应该接收@Aspect?如果是,那么它肯定是 Spring 管理的 bean,因此自动装配应该可以工作?
  2. 如果 context:component-scan 不是用于创建方面,我的方面是如何创建的?我以为 aop:aspectj-autoproxy 只是创建了一个 beanPostProcessor 来代理我的 @Aspect 类?如果它不是 Spring 管理的 bean,它会怎么做?

很明显,你可以看出我不了解事情应该如何从头开始.

Obviously you can tell I don't have an understanding of how things should be working from the ground up.

推荐答案

aspect 是一个单例对象,是在 Spring 容器之外创建的.XML 配置的一个解决方案是使用 Spring 的工厂方法来检索方面.

The aspect is a singleton object and is created outside the Spring container. A solution with XML configuration is to use Spring's factory method to retrieve the aspect.

<bean id="syncLoggingAspect" class="uk.co.demo.SyncLoggingAspect" 
     factory-method="aspectOf" />

使用此配置,方面将被视为任何其他 Spring bean,并且自动装配将正常工作.

With this configuration the aspect will be treated as any other Spring bean and the autowiring will work as normal.

您还必须对 Enum 对象和其他没有构造函数的对象或在 Spring 容器外部创建的对象使用工厂方法.

You have to use the factory-method also on Enum objects and other objects without a constructor or objects that are created outside the Spring container.

这篇关于@Aspect 方面的 Spring 自动装配 bean 为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆