@Aspect方面的Spring autowired bean为null [英] Spring autowired bean for @Aspect aspect is null

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

问题描述

我有以下弹簧配置:

<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为null。不幸的是,我无法找到有关其原因的明确文档。 (为了记录,我的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. 是上下文:组件 - 扫描应该是@Aspect?如果它肯定是一个Spring托管bean,那么自动装配应该有效吗?

  2. 如果上下文:组件扫描不是用于创建方面,我的方面是如何创建的?我认为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.

推荐答案

方面是一个单例对象,是在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对象和其他对象上使用factory-method,而不使用在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 autowired bean为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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