Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AspectJ load time weaving not working on Spring beans

I'm working on a project that uses the Java (not xml) flavour of Spring configuration for wiring up dependencies. It also has profiling logic that should be weaved via AspectJ onto the desired methods (via annotations). The setup is working and I can see classes from my desired package being weaved and profiling information being logged out of them.

The problem is that weaving does not work for @Bean classes. I've enabled debug in aop.xml via:

<weaver options="-XnoInline -Xreweavable -verbose -debug -showWeaveInfo">

And I can see classes in my desired package being weaved, but not the beans in the configuration. If I instantiate the classes directly (not inject them) weaving works.

Unfortunately, I can't post real code here, but here's a dumbed down example:

@Configuration
@EnableLoadTimeWeaving(aspectjWeaving = EnableLoadTimeWeaving.AspectJWeaving.ENABLED)
public class MySpringConfig {
    @Bean
    AnnotatedClass1 annotatedClass1() {
        return new AnnotatedClass1(new AnnotatedClass2());
    }
}

AnnotatedClass1 and AnnotatedClass2 live in the same package and weaving works on the one instantiated directly and not the one returned by the bean.

I've searched through the Spring AOP docs but I can't seem to find anything related to this. There is some magic you need to do for auto-proxying and some limitations for SpringAOP but load time weaving should just work as far as I can tell - I've tried on private methods for example and it worked.

like image 376
Alex Ciminian Avatar asked Mar 12 '14 05:03

Alex Ciminian


1 Answers

The problem was the return type - if I do:

@Bean
Object annotatedClass1() {
    return new AnnotatedClass1(new AnnotatedClass2());
} 

the weaving starts to work for the bean as well. My initial assumption was that it has something to do with Spring caching the bean and not using the weaved version, but this didn’t make sense because:

  • load time weaving is supposed to act at, well… class load time :). Then, it doesn’t matter what the method returns, the class should have the aspects.
  • I’ve actually checked the debug output for both Spring and AspectJ and no mention of my class so it must have been ignored somehow.

This is the first time I’ve used this stuff, so I might be misunderstanding things. If anyone can explain why the return type of the @Bean method has anything to do with weaving I’d be happy to accept your answer instead of this one.

like image 141
Alex Ciminian Avatar answered Oct 02 '22 15:10

Alex Ciminian