使用Spring IoC和JavaConfig配置AspectJ方面? [英] Configuring AspectJ aspects using Spring IoC with JavaConfig?

查看:375
本文介绍了使用Spring IoC和JavaConfig配置AspectJ方面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

正如@SotiriosDelimanolis所建议的那样,在JavaConfig中重写这个应该起作用:

As suggested by @SotiriosDelimanolis, rewriting this as the following in JavaConfig should to work:

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

However, this only seems to work if the Profiler aspect is written in native aspectj .aj syntax. If it is written in Java and annotated with @Aspect, I get the following error message:


方法aspectOf()未定义类型Profiler

The method aspectOf() is undefined for the type Profiler

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

Is there an equivalent way of writing this using JavaConfig for aspects written with @AspectJ syntax?

推荐答案

原来有一个 org.aspectj.lang.Aspects 类专门为此目的提供。似乎LTW添加了 aspectOf()方法,这就是它在XML配置中正常工作的原因,但不是在编译时。

Turns out that there is an org.aspectj.lang.Aspects class to provide for specifically this purpose. 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.

要解决此限制, org.aspectj.lang.Aspects 提供 aspectOf()方法:

To get around this limitation, org.aspectj.lang.Aspects provides a aspectOf() method:

@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 IoC和JavaConfig配置AspectJ方面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆