在目标方法执行前后,进行代码增强 (阻止目标方法的执行 )
环绕通知实现任何通知效果。
案例如下:
案例结构:
第一步:编写代理类。
MyAspect.java
//这里必须要抛异常 public Object around( ProceedingJoinPoint proceedingJoinPoint) throws Throwable { System.out.print("环绕通知 方法前执行"); Object result=proceedingJoinPoint.proceed(); System.out.print("环绕通知 方法后执行"); return result; }
第二步:写ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="OrderService" class="cn.itcast.spring.c_aop.impl.OrderServiceimpl" /> <!-- AspectJ AOP --> <!-- 配置目标 --> <bean id="CustomerService" class="cn.itcast.spring.d_aspectj.CustomerService"></bean> <!-- 配置切面类 --> <bean id="MyAspect" class="cn.itcast.spring.d_aspectj.MyAspect"></bean> <aop:config> <!-- ref引用切面类 --> <aop:aspect ref="MyAspect"> <aop:pointcut expression="execution(* cn.itcast.spring.d_aspectj.CustomerService.*(..))" id="mypointcut2"/> <aop:around method="around" pointcut-ref="mypointcut2"/> </aop:aspect> </aop:config> </beans>
第三步 写Junit测试的代码:
@Test public void testaround() { customerService.delete(); }
第四步 输出结果:
环绕通知 方法前执行 this is delete 环绕通知 方法后执行