1.Spring AOP(基于AspectJ框架的AOP使用)
1.1实现步骤
导入jar包 添加命名空间
配置bean
<bean id="MyAdvice" class="cn.wang.advice.MyAdvice"></bean>
<bean id="PersonService" class="cn.wang.service.PersonService"></bean>
2.编写目标方法
public class PersonService {
public boolean save(String name) {
//自定义异常
//int num = 3 / 0;
System.out.println("PersonService...save--"+name);
return true;
}
}
3.增强处理类
public class MyAdvice {
//前置增强
public void before(JoinPoint joinPoint) {
//获得类名
String className = joinPoint.getTarget().getClass().getSimpleName();
//获得方法名
String method = joinPoint.getSignature().getName();
//获得数据
Object[] args = joinPoint.getArgs();
System.out.println("在目标前增强"+className+"."+method+","+Arrays.toString(args));
}
//后置增强
public void after(JoinPoint joinPoint,boolean flag){
System.out.println("在目标后增强:"+flag);
}
//最终增强
public void finalAdvice() {
System.out.println("最终增强");
}
//异常增强
public void throwAdvice(JoinPoint joinPoint,Exception e) {
System.out.println("发生异常了" + e.getMessage()+e.getClass().getName());
}
//环绕增强
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("。。。。。。。环绕前。。。。。。。。");
//调用目标
Object proceed = joinPoint.proceed();
System.out.println("。。。。。。。环绕后。。。。。。。。");
return proceed;
}
}
4.定义切入点
<aop:pointcut expression="execution(* cn.wang.service..*(..))" id="servicePointCut"/>
5.xml配置文件
<!-- 配置AOP -->
<aop:config>
<!-- 定位连接点,增强处理作用的位置 -->
<aop:pointcut expression="execution(* cn.wang.service..*(..))" id="servicePointCut"/>
<!-- 定义切面 -->
<aop:aspect ref="MyAdvice">
<!-- 前置增强/通知 -->
<aop:before method="before" pointcut-ref="servicePointCut"/>
<!-- 后置增强 -->
<aop:after-returning method="after" pointcut-ref="servicePointCut" returning="flag"/>
<!-- 异常增强,必须抛出异常 -->
<aop:after-throwing method="throwAdvice" pointcut-ref="servicePointCut" throwing="e"/>
<!-- 最终增强 -->
<aop:after method="finalAdvice" pointcut-ref="servicePointCut"/>
<!-- 环绕增强 -->
<aop:around method="around" pointcut-ref="servicePointCut"/>
</aop:aspect>
</aop:config>