在Spring中完全支持AspectJ

时间:2017-02-23 17:05:55

标签: java spring aspectj

我想编写一个不属于Spring bean的方法的建议(Spring Boot 1.4.4.RELEASE):

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

我添加了aspectjrt和spring-instrument(??)依赖项

我添加了@EnableAspectJAutoProxy和@EnableLoadTimeWeaving(aspectjWeaving = AspectJWeaving.ENABLED)注释

我添加了VM参数:

-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

处理bean(postconstruct日志),但没有截获执行。 有没有人对我可能错过的东西有所了解? Thx提前

2 个答案:

答案 0 :(得分:1)

好的,对于那些感兴趣的人来说,这是一个技巧,单例模式处理对LTW和Spring的单例的访问,因此在被LTW编织后可以注入Spring依赖项:

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

答案 1 :(得分:0)

尝试使用@Pointcut注释,如下所示:

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

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