使用SpringIOC和JavaConfig配置AspectJ方面?

使用SpringIOC和JavaConfig配置AspectJ方面?,java,spring,aop,aspectj,spring-java-config,Java,Spring,Aop,Aspectj,Spring Java Config,根据Spring的文档,为了为Spring IOC配置方面,必须在xml配置中添加以下内容: <bean id="profiler" class="com.xyz.profiler.Profiler" factory-method="aspectOf"> <property name="profilingStrategy" ref="jamonProfilingStrategy"/> </bean> 但是,这似乎只有在分析器方面是用本机asp

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

<bean id="profiler" class="com.xyz.profiler.Profiler"
      factory-method="aspectOf">
  <property name="profilingStrategy" ref="jamonProfilingStrategy"/>
</bean>
但是,这似乎只有在
分析器
方面是用本机aspectj
.aj
语法编写的情况下才起作用。如果它是用Java编写的,并用
@Aspect
注释,我会收到以下错误消息:

类型探查器的方法aspectOf()未定义

对于使用@AspectJ语法编写的方面,是否有一种使用JavaConfig编写的等效方法

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

工厂方法
在中的文档中进行了解释。

证明有一个
org.aspectj.lang.Aspects
类专门用于此目的。似乎LTW添加了
aspectOf()
方法,这就是为什么它在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;
}

希望这对以后的其他人有所帮助。

我尝试过,但由于
aspectOf()
未定义,因此出现了编译时错误。“类型探查器的方法aspectOf()未定义”。我以为我做错了。@EricB。我对AspectJ不太了解,无法在这方面为您提供帮助,但是如果您没有为
探查器
类提供
aspectOf
方法,并且AspectJ没有通过其他方式(字节码操作)提供,那么您就无能为力了。您在问题中的XML bean定义与上面的
@bean
方法完全相同。我将假设您在AspectJ设置中遗漏了一些内容。我不确定,但我认为这可能与aspect被定义为
@aspect
有关,Java编译器将其与常规Java类混淆。如果我将方面编写为
.aj
文件,它似乎可以按预期工作。问题是我不知道如何解决这个问题。我已经更新了我的问题以反映新的信息。@EricB。我将留下我的答案,因为它回答了
是否有一种使用JavaConfig写这篇文章的等效方法,但您的问题应该是关于使用Spring配置AspectJ,我对此无能为力:(.这个\@Bean是在哪里定义的?在Config类中?你仍然用@Aspect注释你的建议,并在配置类中使用\@EnableSpectJautoproxy吗?我已经尝试过了,但它看起来不像AspectJ编译时编织开始了。下面是我的示例代码:我使用带有@EnableLoadTimeWeaving的spring java配置(aspectjWeaving=aspectjWeaving.ENABLED)和aop.xml部分中列出的方面。当我们使用aspects.aspectOf定义方面bean时,我得到以下错误:线程“main”中出现异常org.aspectj.lang.NoAspectBoundException:Exception在初始化story.jeff.MyAspect:java.lang.NoSuchMethodException:story.jeff.MyAspect.aspectOf()时,我相信这意味着在创建bean之前还没有编织过aspect。你知道如何解决这个问题吗?
@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;
}