Spring注解配置AOP
首先扫描bean的时候,把写的切面类所在的包给配进去,交给Spring管理
然后加上一句话:
<aop:aspectj-autoproxy/>
启用自动代理,使用注解配置切面
放上切面类代码:
@Pointcut注解表示切入点,他注解的这个类本身没啥吊用,主要是告诉Spring哪些方法会被切
返回值、包名、类名、方法名、参数值都可以指定
package top.yibobo.service.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Service;
@Service
@Aspect
public class LogAspect {
@Pointcut("execution(* top.yibobo.service.*.*(..))")
public void anyMethod(){
}
@Before("anyMethod()")
public void before(JoinPoint joinPoint){
String name=joinPoint.getSignature().getName();
System.out.println(name+"方法即将执行");
}
@AfterReturning("anyMethod()")
public void afterReturn(){
System.out.println("后置通知");
}
@AfterThrowing("anyMethod()")
public void afterThrowing(){
System.out.println("异常通知");
}
@After("anyMethod()")
public void finalMethod(){
System.out.println("最终通知");
}
@Around("anyMethod()")
public Object aroundMethod(ProceedingJoinPoint point) throws Throwable {
System.out.println("环绕通知");
return point.proceed();
}
}
