Thomas Escolan
Thomas Escolan

Reputation: 1125

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

Upvotes: 1

Views: 1102

Answers (2)

Thomas Escolan
Thomas Escolan

Reputation: 1125

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;
    }
}

Upvotes: 1

Sergio Lema
Sergio Lema

Reputation: 1629

Try using the @Pointcut annotation too like this:

@Pointcut("execution(public * com.netflix.appinfo.InstanceInfo.getId())")
public void pointcut() {}

@Around("pointcut()")
public Object whatever(ProceedingJoinPoint joinPoint) throws {...}

Upvotes: 0

Related Questions