1

我在 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,因此未读取属性文件并且日志消息为 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)如何使spring注释与我用@Aspect注释的方面类一起工作?

2)我还想使用弹簧配置文件来启用或禁用方面,并且由于弹簧注释在我的方面不起作用,我不知道如何使这项工作?

提前致谢

4

0 回答 0