spring_aop_注解和xml配置使用
1 package com.example.demo01.aop; 2 3 import org.aspectj.lang.ProceedingJoinPoint; 4 import org.aspectj.lang.annotation.*; 5 import org.springframework.stereotype.Component; 6 7 @Aspect // 声明切面 8 @Component // 注入spring容器 9 public class Aop01 { 10 11 // 前置通知 12 @Before("execution(* com.example.demo01.service.*.add*(..))") 13 public void before() { 14 System.out.println("Before...."); 15 } 16 17 // 后置通知 18 @After("execution(* com.example.demo01.service.*.add*(..))") 19 public void after() { 20 System.out.println("After...."); 21 } 22 23 // 异常通知 24 @AfterThrowing("execution(* com.example.demo01.service.*.add*(..))") 25 public void afterthrowing() { 26 System.out.println("AfterThrowing...."); 27 } 28 29 // 环绕通知 30 @Around("execution(* com.example.demo01.service.*.add*(..))") 31 public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { 32 System.out.println("Around before...."); 33 proceedingJoinPoint.proceed(); 34 System.out.println("Around after...."); 35 } 36 37 38 }
1 <!--开启事务注解权限--> 2 <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
xml
1 package com.example.demo02.aop; 2 3 import org.aspectj.lang.ProceedingJoinPoint; 4 import org.aspectj.lang.annotation.*; 5 import org.springframework.stereotype.Component; 6 7 public class Aop02 { 8 9 // 前置通知 10 public void before() { 11 System.out.println("Before...."); 12 } 13 14 // 后置通知 15 public void after() { 16 System.out.println("After...."); 17 } 18 19 // 异常通知 20 public void afterThrowing() { 21 System.out.println("AfterThrowing...."); 22 } 23 24 25 // 返回后通知 26 public void afterReturning() { 27 System.out.println("afterReturning...."); 28 } 29 30 // 环绕通知 31 public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { 32 System.out.println("Around before...."); 33 proceedingJoinPoint.proceed(); 34 System.out.println("Around after...."); 35 } 36 }
1 <!-- 切面类 --> 2 <bean id="aop" class="com.example.demo02.aop.Aop02"/> 3 <!-- Aop配置 --> 4 <aop:config> 5 <!-- 定义一个切入点表达式: 拦截哪些方法 --> 6 <aop:pointcut id="pt" expression="execution(* com.example.demo02.service..*.add*(..))"/> 7 <!-- 切面 --> 8 <aop:aspect ref="aop"> 9 <aop:around method="around" pointcut-ref="pt"/> 10 <!-- 前置通知: 在目标方法调用前执行 --> 11 <aop:before method="before" pointcut-ref="pt"/> 12 <!-- 后置通知: --> 13 <aop:after method="after" pointcut-ref="pt"/> 14 <!-- 返回后通知 --> 15 <aop:after-returning method="afterReturning" pointcut-ref="pt"/> 16 <!-- 异常通知 --> 17 <aop:after-throwing method="afterThrowing" pointcut-ref="pt"/> 18 </aop:aspect> 19 </aop:config>
浙公网安备 33010602011771号