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

查看:36
本文介绍了使用带有 JavaConfig 的 Spring IoC 配置 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 方面使用原生 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:

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

The method aspectOf() is undefined for the type Profiler

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

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

推荐答案

原来有一个 org.aspectj.lang.Aspects 类专门用于此目的.看起来 aspectOf() 方法是由 LTW 添加的,这就是为什么它在 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;
}

希望这能在未来对其他人有所帮助.

Hope this helps someone else in the future.

这篇关于使用带有 JavaConfig 的 Spring IoC 配置 AspectJ 方面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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