Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

<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:

@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. If it is written in Java and annotated with @Aspect, I get the following error message:

The method aspectOf() is undefined for the type Profiler

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

like image 321
Eric B. Avatar asked Apr 04 '14 02:04

Eric B.


Video Answer


2 Answers

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.

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.

like image 123
Eric B. Avatar answered Oct 19 '22 00:10

Eric B.


Is there an equivalent way of writing this using 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.

like image 1
Sotirios Delimanolis Avatar answered Oct 19 '22 01:10

Sotirios Delimanolis