spring Aop1

工 做忙,時間緊,不過事情再多,學習是必須的。記得之前的部門老大說過:「開發人員不可能一天到晚只有工做,確定是須要自我學習。第一:爲了更充實本身,保 持進步狀態。第二:爲了提高技術,提升開發能力。第三:保持程序員對技術和學習的熱情,工做的激情。程序員仍是須要把基礎打紮實,修煉本身的內功。」 因此趕忙把學習的東西總結一下,加深印象。以前有說了下AOP的原理 (http://www.cnblogs.com/yanbincn/archive/2012/06/01/2530377.html) 。基於代理模式,瞭解了jdk動態代理和cglib的用法。可是在真正的使用AOP的時候,不可能寫這麼厚重的方法。html

  Spring有兩大核 心,IOC和AOP。IOC在java web項目中無時無刻不在使用。然而AOP用的比較少,的確也是通常的項目用的場所很少。事務控制基本都用,但倒是Spring封裝的不須要咱們再去實 現,但Spring的AOP遠不止這些,不能由於項目中沒有使用,而不去學習及理解。我以爲這是做爲一個java web軟件開發人員必須具有的技能。業內不少將AOP應用在日誌記錄上,惋惜咱們項目沒這麼作,後面須要學習下。在這先把Spring AOP的基本用法,在腦子裏理一邊,作一次積累。java

一、概念術語  程序員

  在開始以前,須要理解Spring aop 的一些基本的概念術語(總結的我的理解,並不是Spring官方定義):web

  切面(aspect):用來切插業務方法的類。spring

  鏈接點(joinpoint):是切面類和業務類的鏈接點,其實就是封裝了業務方法的一些基本屬性,做爲通知的參數來解析。數組

  通知(advice):在切面類中,聲明對業務方法作額外處理的方法。app

  切入點(pointcut):業務類中指定的方法,做爲切面切入的點。其實就是指定某個方法做爲切面切的地方。ide

  目標對象(target object):被代理對象。學習

  AOP代理(aop proxy):代理對象。測試

  通知:

  前置通知(before advice):在切入點以前執行。

  後置通知(after returning advice):在切入點執行完成後,執行通知。

  環繞通知(around advice):包圍切入點,調用方法先後完成自定義行爲。

  異常通知(after throwing advice):在切入點拋出異常後,執行通知。

二、Spring AOP環境

  要在項目中使用Spring AOP 則須要在項目中導入除了spring jar包以外,還有aspectjweaver.jar,aopalliance.jar ,asm.jar 和cglib.jar 。

好了,前提工做準備完成,Spring 提供了不少的實現AOP的方式,在學習過程當中,按部就班。進行Spring 接口方式,schema配置方式和註解的三種方式進行學習。好了廢話很少說了,開始spring aop學習之旅:

三、方式一:AOP接口

  利用Spring AOP接口實現AOP,主要是爲了指定自定義通知來供spring AOP機制識別。主要接口:前置通知 MethodBeforeAdvice ,後置通知:AfterReturningAdvice,環繞通知:MethodInterceptor,異常通知:ThrowsAdvice 。見例子代碼:

a、業務接口:

複製代碼
/** * 代理類接口,也是業務類接口<br> * * 利用接口的方式,spring aop 將默認經過jdk 動態代理來實現代理類<br> * 不利用接口,則spring aop 將經過cglib 來實現代理類 * * @author yanbin * */ public interface IBaseBusiness { /** * 用做代理的切入點方法 * * @param obj * @return */ public String delete(String obj); /** * 這方法不被切面切 * * @param obj * @return */ public String add(String obj); /** * 這方法切不切呢?能夠設置 * * @param obj * @return */ public String modify(String obj); }
複製代碼

b、業務類:

複製代碼
/** * 業務類,也是目標對象 * * @author yanbin * */ public class BaseBusiness implements IBaseBusiness { /** * 切入點 */ public String delete(String obj) { System.out.println("==========調用切入點:" + obj + "說:你敢刪除我!===========\n"); return obj + ":瞄~"; } public String add(String obj) { System.out.println("================這個方法不能被切。。。============== \n"); return obj + ":瞄~ 嘿嘿!"; } public String modify(String obj) { System.out.println("=================這個也設置加入切吧====================\n"); return obj + ":瞄改瞄啊!"; } }
複製代碼

c、通知類:

前置通知:

複製代碼
/** * 前置通知。 * * @author yanbin * */ public class BaseBeforeAdvice implements MethodBeforeAdvice { /** * method : 切入的方法 <br> * args :切入方法的參數 <br> * target :目標對象 */ @Override public void before(Method method, Object[] args, Object target) throws Throwable { System.out.println("===========進入beforeAdvice()============ \n"); System.out.print("準備在" + target + "對象上用"); System.out.print(method + "方法進行對 '"); System.out.print(args[0] + "'進行刪除!\n\n"); System.out.println("要進入切入點方法了 \n"); } }
複製代碼

後置通知:

複製代碼
/** * 後置通知 * * @author yanbin * */ public class BaseAfterReturnAdvice implements AfterReturningAdvice { /** * returnValue :切入點執行完方法的返回值,但不能修改 <br> * method :切入點方法 <br> * args :切入點方法的參數數組 <br> * target :目標對象 */ @Override public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { System.out.println("==========進入afterReturning()=========== \n"); System.out.println("切入點方法執行完了 \n"); System.out.print(args[0] + "在"); System.out.print(target + "對象上被"); System.out.print(method + "方法刪除了"); System.out.print("只留下:" + returnValue + "\n\n"); } }
複製代碼

環繞通知:

複製代碼
/** * 環繞通知 * * @author yanbin * */ public class BaseAroundAdvice implements MethodInterceptor { /** * invocation :鏈接點 */ @Override public Object invoke(MethodInvocation invocation) throws Throwable { System.out.println("===========進入around環繞方法!=========== \n"); // 調用目標方法以前執行的動做 System.out.println("調用方法以前: 執行!\n"); // 調用方法的參數 Object[] args = invocation.getArguments(); // 調用的方法 Method method = invocation.getMethod(); // 獲取目標對象 Object target = invocation.getThis(); // 執行完方法的返回值:調用proceed()方法,就會觸發切入點方法執行 Object returnValue = invocation.proceed(); System.out.println("===========結束進入around環繞方法!=========== \n"); System.out.println("輸出:" + args[0] + ";" + method + ";" + target + ";" + returnValue + "\n"); System.out.println("調用方法結束:以後執行!\n"); return returnValue; } }
複製代碼

異常通知:

複製代碼
/** * 異常通知,接口沒有包含任何方法。通知方法自定義 * * @author yanbin * */ public class BaseAfterThrowsAdvice implements ThrowsAdvice { /** * 通知方法,須要按照這種格式書寫 * * @param method * 可選:切入的方法 * @param args * 可選:切入的方法的參數 * @param target * 可選:目標對象 * @param throwable * 必填 : 異常子類,出現這個異常類的子類,則會進入這個通知。 */ public void afterThrowing(Method method, Object[] args, Object target, Throwable throwable) { System.out.println("刪除出錯啦"); } }
複製代碼

d、定義指定切點:

複製代碼
/** * 定義一個切點,指定對應方法匹配。來供切面來針對方法進行處理<br> * * 繼承NameMatchMethodPointcut類,來用方法名匹配 * * @author yanbin * */ public class Pointcut extends NameMatchMethodPointcut { private static final long serialVersionUID = 3990456017285944475L; @SuppressWarnings("rawtypes") @Override public boolean matches(Method method, Class targetClass) { // 設置單個方法匹配 this.setMappedName("delete"); // 設置多個方法匹配 String[] methods = { "delete", "modify" }; //也能夠用「 * 」 來作匹配符號 // this.setMappedName("get*"); this.setMappedNames(methods); return super.matches(method, targetClass); } }
複製代碼

e、配置: 

複製代碼
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd" default-autowire="byName"> <!-- ==============================利用spring本身的aop配置================================ --> <!-- 聲明一個業務類 --> <bean id="baseBusiness" class="aop.base.BaseBusiness" /> <!-- 聲明通知類 --> <bean id="baseBefore" class="aop.base.advice.BaseBeforeAdvice" /> <bean id="baseAfterReturn" class="aop.base.advice.BaseAfterReturnAdvice" /> <bean id="baseAfterThrows" class="aop.base.advice.BaseAfterThrowsAdvice" /> <bean id="baseAround" class="aop.base.advice.BaseAroundAdvice" /> <!-- 指定切點匹配類 --> <bean id="pointcut" class="aop.base.pointcut.Pointcut" /> <!-- 包裝通知,指定切點 --> <bean id="matchBeforeAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor"> <property name="pointcut"> <ref bean="pointcut" /> </property> <property name="advice"> <ref bean="baseBefore" /> </property> </bean> <!-- 使用ProxyFactoryBean 產生代理對象 --> <bean id="businessProxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <!-- 代理對象所實現的接口 ,若是有接口能夠這樣設置 --> <property name="proxyInterfaces"> <value>aop.base.IBaseBusiness</value> </property> <!-- 設置目標對象 --> <property name="target"> <ref local="baseBusiness" /> </property> <!-- 代理對象所使用的攔截器 --> <property name="interceptorNames"> <list> <value>matchBeforeAdvisor</value> <value>baseAfterReturn</value> <value>baseAround</value> </list> </property> </bean> </beans>
複製代碼

f、測試類:

複製代碼
public class Debug { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("aop/schema_aop.xml"); IBaseBusiness business = (IBaseBusiness ) context.getBean("businessProxy"); business.delete("貓"); } }
複製代碼

g、測試結果:運行下測試類,清晰明瞭。因爲結果呈現太長就不貼了。

  具體的代碼實現能夠從代碼註釋中很容易理解 接口方式的實現。結果也可想而知,前置方法會在切入點方法以前執行,後置會在切入點方法執行以後執行,環繞則會在切入點方法執行前執行同事方法結束也會執 行對應的部分。主要是調用proceed()方法來執行切入點方法。來做爲環繞通知先後方法的分水嶺。而後在實現的過程當中,有幾點倒是能夠細揣摩一下的。

  能夠看出在xml 配置 businessProxy這個bean的時候,ProxyFactoryBean類中指定了,proxyInterfaces參數。這裏我把他配置了 IBaseBusiness接口。由於在項目開發過程當中,每每業務類都會有對應的接口,以方便利用IOC解耦。但Spring AOP卻也能支持沒有接口的代理。這就是爲何須要導入cglib.jar的包了。看過spring的源碼,知道在目標切入對象若是有實現接 口,spring會默認走jdk動態代理來實現代理類。若是沒有接口,則會經過cglib來實現代理類。

  這個業務類如今有 前置通知,後置通知,環繞三個通知同時做用,可能以及更多的通知進行做用。那麼這些通知的執行順序是怎麼樣的?就這個例子而言,同時實現了三個通知。在例 子xml中,則顯示執行before通知,而後執行around的前處理,執行切點方法,再執行return處理。最後執行around的後處理。通過測 試,知道spring 處理順序是按照xml配置順序依次處理通知,以隊列的方式存放前通知,以壓棧的方式存放後通知。因此是前通知依次執行,後通知到切入點執行完以後,從棧裏 在後進先出的形式把後通知執行。

  在實現過程當中發現通知執行對應目標對象的整個類中的方法,如何精確到某個方法,則須要定義一個切點匹配的方式:spring提供了方法名匹配或正則方式來匹配。而後經過DefaultPointcutAdvisor來包裝通知,指定切點。

相關文章
相關標籤/搜索