简体   繁体   中英

Aspect never gets called

My goal is to execute some code each time a method with a particular annotation completes its execution. I have the following:

@Aspect
public class MonitoringAspect {
    @After("@annotation(MonitorExecution)")
    public void onFinished(JoinPoint jp) {
        System.out.println("called!");
    }
}

The code of the MonitorExecution annotation is as follows:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MonitorExecution {
}

This happens inside a Spring4 application and I have declared the MonitoringAspect as a bean like:

<bean id="monitoringAspect" class="com.....MonitoringAspect" />
<aop:aspectj-autoproxy proxy-target-class="true">
    <aop:include name="monitoringAspect"/>
</aop:aspectj-autoproxy>

I have a public method inside a general-purpose class (ie not managed by spring / not a component) that is annotated with the @MonitorExecution annotation. I have successfully verified that the aforementioned method gets called, but the aspect is never triggered. Any ideas what might be the issue?

aspectj-autoproxy means that proxy classes will be created for each Spring managed bean (using JDK dynamic proxies or CGLIB) and using these proxies you are able to intercept methods invocation. Thus, if your annotated method is method of a class outside Spring Context, aspect will not work

Despite it if you still want to intercept it, you will have to use AspectJ only or in conjunction with Spring. For second option you will have to enable load-time weaving in your spring configuration

Have a look documentation for details: https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM