當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring AOP(面向切面) 注解使用方法
生活随笔
收集整理的這篇文章主要介紹了
Spring AOP(面向切面) 注解使用方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 開啟自動織入支持
- 在XML中開啟
- 通過注解開啟
- 注解方式入口類
- 注解方式定義切面類
- Spring的注解的AOP的通知類型
- 環繞通知@Around
- @Before:前置通知
- @AfterReturning:后置通知
- @AfterThrowing:異常拋出通知
- @After:最終通知
- 通過@Pointcut注解定義切入點表達式
開啟自動織入支持
在XML中開啟
添aop標簽
<aop:aspectj-autoproxy />開啟注解支持,同時強制指定代理機制為cglib
<aop:aspectj-autoproxy proxy-target-class="true" />通過注解開啟
@Configuration
// 開啟注解支持,同時強制指定代理機制為cglib
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class MyAOPConf {}
@Component
@Aspect //表示這是一個切面類,里面的方法都是像打印日志等圍繞業務方法的方法
注解方式入口類
@Configuration //相當生成一個XML文件 @ComponentScan(basePackages = "com.lanou3g.spring.simple.say")//掃描路徑 @EnableAspectJAutoProxy //開啟對AOP相關注解的處理 public class AppByAnnotation { ... }注解方式定義切面類
@Pointcut:切入點的注解
由于@Aspect注解沒有讓Spring作為組件bean掃描的能力,所以我們需要額外添加@Component注解
Spring的注解的AOP的通知類型
環繞通知@Around
指定該方法是一個環繞通知,通知注解的參數代表引用一個切入點表達式
@Around("com.lanou3g.spring.GlobalPointcut.say_all_method()")public Object aroundM(ProceedingJoinPoint joinPoint) throws Throwable {} // 獲取連接點方法的名稱String methodName = joinPoint.getSignature().getName();// 獲取連接點方法的參數Object[] args = joinPoint.getArgs();@Before:前置通知
@Before("com.lanou3g.spring.GlobalPointcut.say_all_method()")@AfterReturning:后置通知
@AfterReturning(pointcut = "com.lanou3g.spring.GlobalPointcut.say_all_method()", returning = "ret")@AfterThrowing:異常拋出通知
@AfterThrowing(value="execution(* "com.lanou3g.spring.GlobalPointcut.say_all_method()" , throwing="e")@After:最終通知
@After("com.lanou3g.spring.GlobalPointcut.say_all_method()")| Signature getSignature(); | 獲取封裝了署名信息的對象,在該對象中可以獲取到目標方法名,所屬類的Class等信息 |
| Object[] getArgs(); | 獲取傳入目標方法的參數對象 |
| Object getTarget(); | 獲取被代理的對象 |
| Object getThis(); | 獲取代理對象 |
| Object proceed() throws Throwable | 執行目標方法 |
| Object proceed(Object[] var1) throws Throwable | 傳入的新的參數去執行目標方法 |
通過@Pointcut注解定義切入點表達式
攔截com.lanou3g.spring.simple.say包下所有類(包括子包中所有類)中的所有方法
@Pointcut(“execution(* com.lanou3g.spring.simple.say….(…))”)
public void say_all_method() {}
總結
以上是生活随笔為你收集整理的Spring AOP(面向切面) 注解使用方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 长尾效应--Long Tail Effe
- 下一篇: 敏涵控股集团成为2022第十二届公益节候