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

问题描述

事实证明,有一个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;
}

解决方法

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

<bean id="profiler" class="com.xyz.profiler.Profiler"
      factory-method="aspectOf">
  <property name="profilingStrategy" ref="jamonProfilingStrategy"/>
</bean>

正如@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;
}

但是,这仅在Profiler方面以本机方面j .aj语法编写时才起作用。如果它是用Java编写并带有注释的@Aspect,则会收到以下错误消息:

未为Profiler类型定义方法AspectOf()

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