使用Spring IoC和JavaConfig配置AspectJ方面?

Eri*_* B. 7 java aop spring aspectj spring-java-config

根据Spring的文档使用Spring IoC配置AspectJ方面以配置Spring IOC的方面,必须在xml配置中添加以下内容:

<bean id="profiler" class="com.xyz.profiler.Profiler"
      factory-method="aspectOf">
  <property name="profilingStrategy" ref="jamonProfilingStrategy"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

正如@SotiriosDelimanolis所建议的那样,在JavaConfig中将以下内容重写为:

@Bean
public com.xyz.profiler.Profiler profiler() {
    com.xyz.profiler.Profiler profiler = com.xyz.profiler.Profiler.aspectOf();
    profiler.setProfilingStrategy(jamonProfilingStrategy()); // assuming you have a corresponding @Bean method for that bean
    return profiler;
}
Run Code Online (Sandbox Code Playgroud)

但是,如果Profiler方面是用native aspectj .aj语法编写的,这似乎只能起作用.如果它是用Java编写的并带有注释@Aspect,我会收到以下错误消息:

对于类型Profiler,方法aspectOf()未定义

对于使用@AspectJ语法编写的方面,是否有使用JavaConfig编写此方法的等效方法?

Eri*_* B. 14

事实证明,有一个org.aspectj.lang.Aspects专门为此目的提供的课程.似乎aspectOf()LTW添加了该方法,这就是它在XML配置中正常工作的原因,但在编译时却没有.

为了解决这个限制,org.aspectj.lang.Aspects提供了一种aspectOf()方法:

@Bean
public com.xyz.profiler.Profiler profiler() {
    com.xyz.profiler.Profiler profiler = Aspects.aspectOf(com.xyz.profiler.Profiler.class);
    profiler.setProfilingStrategy(jamonProfilingStrategy()); // assuming you have a corresponding @Bean method for that bean
    return profiler;
}
Run Code Online (Sandbox Code Playgroud)

希望这有助于将来的其他人.