Aop注解:
<1>使用注解先导入context命名空间
<?xml version="1.0" encoding="UTF-8"?>
<2>配置spring使其支持aop 注解
在xml文件中添加 aop:aspectj-autoproxy/
<3>配置切面:在通知类的前面加上注解 @Aspect
<4>配置切点 在通知类中添加代码
@PointCut(“execution = ( * ….(…))")
private void pt1(){}
注意这里的pt1就是切入点,就相当于xml文件中配置的pointCut 的id=pt1
<5>使用注释注明通知类型
a.前置通知:在通知前面加上备注 @Before(“pt1”) 或者 @before(value = "execution=( * ….(…))”)
b.后置通知:在通知前面加上备注 @AfterReturning(“pt1”) 或者 同上
c.异常通知:在通知前面加上备注 @AfterThrowing(“pt1”) 或者 同上
d.环绕通知:在通知前面加上备注 @ @Around(“pt1()”) 或者 同上
代码:`package Util;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
-
@author 刘棋军
-
@date2019-02-21
*/
@Component(“logger”)
@Aspect
public class CustomerLogger {//切入点配置
@Pointcut(“execution(* com.liuqijun.spring.CustomerServerImp.update(…))”)
private void pt1(){}@Before(value = “execution(* com.liuqijun.spring.CustomerServerImp.update(…))”)
public void beforAdvice(){
System.out.println(“前置通知!”);
}@AfterReturning(value = “execution(* com.liuqijun.spring.CustomerServerImp.update(…))”)
public void afterReturn(){
System.out.println(“后置通知”);
}@After(value = “execution(* com.liuqijun.spring.CustomerServerImp.update(…))”)
public void after(){
System.out.println(“最终通知”);
}@AfterThrowing(value = “execution(* com.liuqijun.spring.CustomerServerImp.update(…))”)
public void throwing(){
System.out.println(“异常通知通知”);
}/**
- spring提供了ProceedingJoinPoint接口:用来做为环绕通知的形参
- ProceedinngJoinPoint有个proceed方法就相当method.invoke()
- 环绕通知可以通过手写代码的位置来指定通知类型,之前是在xml文件中配置,在环绕通知中通知与调用切入点的相对位置确定了它的类型
/
// @Around(value = "execution( com.liuqijun.spring.CustomerServerImp.*(…))")
public Object around(ProceedingJoinPoint pjp){
System.out.println(“环绕通知”);
Object retValue = null;
//调用切入点
try {
System.out.println(“huanrao 前置通知”);
retValue= pjp.proceed();
System.out.println(“huanrao 后置通知”);
} catch (Throwable throwable) {
throwable.printStackTrace();
}finally{
System.out.println(“huanrao 最终通知”);
}
return retValue;
}
}
`
1715

被折叠的 条评论
为什么被折叠?



