Thomas Escolan Thomas Escolan -4 years ago 155
Java Question

Full AspectJ support in Spring

I'd like to weave an advice on a method that is NOT part of a Spring bean (Spring Boot 1.4.4.RELEASE) :

@Component
@Aspect
...
@Around("execution(public * com.netflix.appinfo.InstanceInfo.getId())")


I added aspectjrt and spring-instrument (??) dependencies

I added @EnableAspectJAutoProxy and @EnableLoadTimeWeaving(aspectjWeaving = AspectJWeaving.ENABLED) annotations

I added VM arguments:

-javaagent:d:\.m2\repository\org\springframework\spring-instrument\4.3.6.RELEASE\spring-instrument-4.3.6.RELEASE.jar
-javaagent:d:\.m2\repository\org\aspectj\aspectjweaver\1.8.9\aspectjweaver-1.8.9.jar


The bean is handled (postconstruct log) but the execution isn't intercepted.
Does anyone has a clue on something I could miss ? Thx in advance

Answer Source

Ok, here is the trick for those interested, a singleton pattern is handling access to a singleton for both LTW and Spring, so it can be injected with Spring dependencies after being weaved by LTW:

@Configuration
@Aspect
public class MyAspect {
    @Value("${mycompany.property}")
    private String myKey;

    @Around("execution(public * com.mycompany.NotASpringean.getProperty())")
    public String weave(ProceedingJoinPoint jp) throws Throwable {
        String value = (String) jp.proceed();
        // transform the value thx to injected myKey value
        return value;
    }

    @Bean("post-construct-aspect")
    public MyAspect init() {
        return MyAspect.aspectOf(); // get existing instance via factory method
    }

    private static MyAspect instance = new MyAspect();
    /** Singleton pattern used by LTW then Spring */
    public static MyAspect aspectOf() {
        return instance;
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download