Search code examples
springspring-bootaspectjload-time-weaving

Spring - @Configurable classes in external JAR


I want to use spring dependency injection for my domain classes, that are possibly not created within spring context. That's why I have annotated these classes with @Configurable annotation and I try to setup load time weaving. My spring configuration is :

@SpringBootApplication
@EnableSpringConfigured
@EnableAspectJAutoProxy
@EnableCaching(mode = AdviceMode.ASPECTJ)
@EnableLoadTimeWeaving
public class WebApplication extends WebMvcConfigurerAdapter

This works fine but only if my @Configurable classes are in same JAR as my main Spring Boot application. However I want to have my @Configurable domain classes in JAR that is added as dependency for main application.

I tried this but it looks like load time weaving is not working for external JARs. Do you have any suggestions how to solve this issue?

EDIT
I have added -verbose:class to my JVM options and I have found out that classes from external JARs are loaded by class loader before LoadTimeWeaving is configured and initialized. And classes not in external JAR are loaded as they are needed i.e. after LoadTimeWeaving init.

So basically my question is :
Is it possible to initialize LTW before external JARs loading? Or is it possible to reload (or make AspectJ enhancement) classes after LTW is configured?

EDIT 2
I found out the reason why my classes from external jar are loadded before LTW init. It's because these classes are also annotated with @Entity annotation. Therefore they are loaded during hibernate initialization which occure before LTW init.

So the final question is: :D
How to assume that LTW is initialized before hibernate (and possibly other) initializations?


Solution

  • Ok I have a solution. :) As I sad issue was the order of spring bean initialization. So I simple had to ensure that load time weaver was initialized before hibernate. Simply injecting LoadTimeWeaver into my configuration class was the workaround:

        @Autowired
        private LoadTimeWeaver loadTimeWeaver;
    

    EDIT
    Another solution is to add aspectjweaver.jar as javaagent in addition to spring-instrument.