在@Aspect类的编译时编织中@Autowired依赖项为null

时间:2015-07-08 11:06:45

标签: spring spring-boot aspectj spring-aop aspectj-maven-plugin

我在maven项目中有一个方面类:my-aspect-project

@Aspect
public class LoggingAspect {

@Autowired
public MessageSource messageSource

@Pointcut("execution(@Log * *(..))")
public void executionOfLogAnnotationMethod(){}

@Before(value= "executionOfLoggableAnnotationMethod")
public void logBefore(JointPoint jp){
Logger.log(Level.info,messageSource.getMessage("before.log.message"),new String[] {
jp.getTarget().getClass().getSimpleName(),
jp.getSignature().getName(), 
Arrays.deepToString(jp.getArgs())
});

}

我已经使用了aspectj-maven-plugin在maven中进行编译时编织,如下所示

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>${aspectj-maven-plugin-version}</version>
<executions>
<execution>
<phase>process-sources</phase>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
<configuration>
<complianceLevel>${maven.compiler.source}</complianceLevel>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<encoding>${project.build.sourceEncoding}</encoding>
<showWeaveInfo>true</showWeaveInfo>
<forceAjcCompile>true</forceAjcCompile>
<verbose>true</verbose>
<Xlint>warning</Xlint>
<aspectLibraries>
<aspectLibrary>
<groupId>com.mycompany-myproject</groupId>
<artifactId>my-aspect-project</artifactId>
</aspectLibrary>
</aspectLibraries>
</configuration>
</execution>
</executions>
</plugin>

Aspect按预期工作,只要调用使用@Log注释的方法,就会调用通知,但在aspect中自动装配的messageSource因为结果为null,则不读取属性文件,并且日志消息为空。

我正在使用spring boot应用程序,并且没有使用xml。

我读了这个[http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html#aop-aj-configure],我不确定这在我的情况下会如何起作用,

我尝试在Appconfig中定义bean,如下所示,

@Bean()
public LoggingAspect loggingAspect() {
    LoggingAspect loggerAspect =  Aspects.aspectOf(LoggingAspect.class);
    loggerAspect.messageSource = messageSource;//Autowired in same class
    return loggerAspect;
}

这也行不通。我还在bean方法loggingAspect()中添加了一个调试点,它根本没有被调用。

所以请告诉我,

1)如何使用弹簧注释来处理使用@Aspect注释的方面类?

2)我也想使用弹簧配置文件启用或禁用方面,因为弹簧注释在我的方面不起作用,我不知道如何使这个工作?

先谢谢

0 个答案:

没有答案