[英]Configuring AspectJ aspects using Spring IoC with JavaConfig?
According to Spring's Documentation Configuring AspectJ aspects using Spring IoC in order to configure an aspect for Spring IOC, the following has to be added to the xml configuration: 根据Spring的文档使用Spring IoC配置AspectJ方面以配置Spring IOC的方面,必须在xml配置中添加以下内容:
<bean id="profiler" class="com.xyz.profiler.Profiler"
factory-method="aspectOf">
<property name="profilingStrategy" ref="jamonProfilingStrategy"/>
</bean>
As suggested by @SotiriosDelimanolis, rewriting this as the following in JavaConfig should to work: 正如@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;
}
However, this only seems to work if the Profiler
aspect is written in native aspectj .aj
syntax. 但是,如果
Profiler
方面是用native aspectj .aj
语法编写的,这似乎只能起作用。 If it is written in Java and annotated with @Aspect
, I get the following error message: 如果它是用Java编写的并使用
@Aspect
注释,则会收到以下错误消息:
The method aspectOf() is undefined for the type Profiler
对于类型Profiler,方法aspectOf()未定义
Is there an equivalent way of writing this using JavaConfig for aspects written with @AspectJ syntax? 对于使用@AspectJ语法编写的方面,是否有使用JavaConfig编写此方法的等效方法?
Turns out that there is an org.aspectj.lang.Aspects
class to provide for specifically this purpose. 事实证明,有一个
org.aspectj.lang.Aspects
类专门用于此目的。 It appears that the aspectOf()
method is added by the LTW which is why it works fine in XML configuration, but not at compile time. 看来,LTW添加了
aspectOf()
方法,这就是为什么它在XML配置中工作正常,但在编译时却没有。
To get around this limitation, org.aspectj.lang.Aspects
provides a aspectOf()
method: 为了解决这个限制,
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;
}
Hope this helps someone else in the future. 希望这有助于将来的其他人。
Is there an equivalent way of writing this using JavaConfig?
是否有使用JavaConfig编写此方法的等效方法?
Almost always. 几乎总是。
@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;
}
The factory-method
is explained in the documentation in Instantiation with a static factory method . factory-method
在Instantiation中的文档中用静态工厂方法进行了解释 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.