spring aop实战
首先声明一个切面类,注册到容器。
@Aspect
@Component
public class SpringAspect {
@Before("pointcut()")
public void before(){
System.out.println("before aspect");
}
@After("pointcut()")
public void after(){
System.out.println("after aspect");
}
@Around("pointcut()")
public void around(ProceedingJoinPoint point){
System.out.println("around before point");
try {
point.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
System.out.println("around after point");
}
@Pointcut("execution(public * com.personal.practice.spring.aop..*.aopTest())")
//方法名为pointcut的签名,可以在@Before等注解中使用
public void pointcut(){
System.out.println("Pointcut");
}
@AfterReturning("pointcut()")
public void afterReturn(){
System.out.println("afterReturn");
}
@AfterThrowing("pointcut()")
public void afterThrowing(){
System.out.println("afterThrowing");
}
}
注意到@Aroundd接受ProceedingJoinPoint类型入参,并且需要调用proceed方法通知目标,否则不会执行target方法。
业务代码:
public interface AopTargetService {
void aopTest();
}
@Component
public class AopTargetServiceImpl implements AopTargetService {
@Override
public void aopTest() {
System.out.println("aopTest service");
}
}
测试用例:
@Test
public void aopTest(){
aopTargetService.aopTest();
}
测试结果:

如果我们不调用ProceedingJoinPoint的proceed方法呢?
结果:

可以看到@before和taget方法都没执行 而after,afterReturn是会执行的。
附
《切面表达式使用姿势》:
转载:https://www.cnblogs.com/zhangxufeng/p/9160869.html
《一个切面中各个连接点的执行顺序》:
转载:https://blog.csdn.net/u012843873/article/details/80540499

浙公网安备 33010602011771号