7

根据 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切面是用原生 aspectj.aj语法编写的情况下才有效。如果它是用 Java 编写并用 注释的@Aspect,我会收到以下错误消息:

类型 Profiler 的方法 aspectOf() 未定义

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

4

2 回答 2

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;
}

希望这对将来的其他人有所帮助。

于 2014-04-04T20:12:01.890 回答
1

是否有使用 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;
}

在Instantiation with a static factory methodfactory-method的文档中对此进行了解释。

于 2014-04-04T03:20:19.047 回答