Spring AOP ANNOTATION 不起作用的问题
问题介绍
1 在Spring配置文件中定义了
<aop:aspectj-autoproxy/>
<context:component-scan base-package="demo">
<context:include-filter type="annotation"
expression="org.aspectj.lang.annotation.Aspect"/>
</context:component-scan>
2 MyAspect.java 代码
package demo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
public class MyAspect {
@Around("execution(* demo.*.*(..))")
public void m1(ProceedingJoinPoint jp) throws Throwable {
System.out.println(jp.getThis().getClass().getName());
System.out.println(jp.getTarget().getClass().getName());
if(jp.getTarget().getClass() == HelloWorldB.class){
System.out.println("HelloWorldB return");
}else{
System.out.println("HelloWorldA proceed");
jp.proceed(jp.getArgs());
}
}
}
3 但是aspect就是不起作用
annotation有了
自动发现bean有了
启用aspectj有了
后来发现因为aspect缺少<span style="font-family: Arial, Helvetica, sans-serif;">@Component标注</span><pre name="code" class="java">导致spring没发现这个bean所以就不能自动化加载了
如果不用bean自动加载,就需要明确在配置文件中定义这个aspect
正确代码
package demo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class MyAspect {
@Around("execution(* demo.*.*(..))")
public void m1(ProceedingJoinPoint jp) throws Throwable {
System.out.println(jp.getThis().getClass().getName());
System.out.println(jp.getTarget().getClass().getName());
if(jp.getTarget().getClass() == HelloWorldB.class){
System.out.println("HelloWorldB return");
}else{
System.out.println("HelloWorldA proceed");
jp.proceed(jp.getArgs());
}
}
}