Spring Boot如何使用AOP實例解析
AOP在開發中的用處還是很廣的,它的設計模式是代理模式,里面的原則就是在不改變源碼的基礎上增加一些新的功能。比如說項目上線了,但是發現項目中的某個模塊運行的很慢,這個時候就需要打印日志去查看,那么可以使用AOP把代碼動態的嵌入到項目中,如果檢測完成,移除它就可以了。
下面來看一下,它在Spring Boot中是如何使用的。
package com.zl.aop.component;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.*;import org.springframework.stereotype.Component;//聲明這是一個組件@Component//定義他是一個切面@Aspectpublic class LogComponent { //定義攔截規則第一個*表示方法返回值任意 //com.zl.aop.Service.*.*的意思是:這個包里面任意類里面的任意方法, //(..)表示參數任意, @Pointcut('execution(* com.zl.aop.Service.*.*(..))') public void pc(){ } //前置通知 @Before(value ='pc()') public void before(JoinPoint jp){ //name就是拿到的Service中的方法名 String name = jp.getSignature().getName(); System.out.println('before:'+name); } //后置通知 @After(value ='pc()') public void after(JoinPoint jp){ //name就是拿到的Service中的方法名 String name = jp.getSignature().getName(); System.out.println('after:'+name); } //返回通知(有返回值就會觸發這個方法) @AfterReturning(value ='pc()',returning = 'result') public void afterReturning(JoinPoint jp,Object result){ //name就是拿到的Service中的方法名 String name = jp.getSignature().getName(); System.out.println('afterReturning:'+name+'---'+result); } //異常通知 @AfterThrowing(value ='pc()',throwing = 'e') public void afterThrowing(JoinPoint jp,Exception e){ //name就是拿到的Service中的方法名 String name = jp.getSignature().getName(); System.out.println('afterThrowing:'+name+'---'+e); } //環繞通知(相當于前四個通知的綜合) @Around(value ='pc()') public Object arount(ProceedingJoinPoint pjp) throws Throwable { //proceed就是Service中方法的返回值 Object proceed = pjp.proceed(); //這個return會篡改方法的返回值并輸出他 return proceed+'java'; }}
就是定義一個組件,去獲取Service中方法,并對他處理。
看一下運行結果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
