SpringAop
注解配置方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| package com.xxxx.aspect;
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component;
@Component @Aspect public class LogCut {
@Pointcut("execution(* com.xxxx.service..*.*(..))") public void cut(){
}
@Before(value = "cut()") public void before() { System.out.println("前置通知..."); }
@AfterReturning(value = "cut()") public void afterReturn(){ System.out.println("返回通知..."); }
@After(value = "cut()") public void after(){ System.out.println("最终通知..."); }
@AfterThrowing(value = "cut()", throwing = "e") public void afterThrow(Exception e){ System.out.println("异常通知... ===== 异常原因:" + e.getMessage()); }
@Around(value = "cut()") public Object around(ProceedingJoinPoint pjp) { System.out.println("环绕通知-前置通知...");
Object object = null;
try{ object = pjp.proceed(); System.out.println(pjp.getTarget()); System.out.println("环绕通知-返回通知..."); } catch (Throwable throwable){ throwable.printStackTrace(); System.out.println("环绕通知-异常通知..."); } System.out.println("环绕通知-最终通知...");
return object; }
}
|
xml文件配置方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.xxxx"/>
<aop:config> <aop:aspect ref="logCut02"> <aop:pointcut id="cut" expression="execution(* com.xxxx.service..*.*(..))"/> <aop:before method="before" pointcut-ref="cut"/> <aop:after-returning method="afterReturn" pointcut-ref="cut"/> <aop:after method="after" pointcut-ref="cut"/> <aop:after-throwing method="afterThrow" pointcut-ref="cut" throwing="e" /> <aop:around method="around" pointcut-ref="cut"/> </aop:aspect> </aop:config>
</beans>
|
源代码 https://github.com/Breeze1203/JavaAdvanced/tree/main/springboot-demo/spring-aop-demo