Spring AOP動態代理原理與實現方式

來源:互聯網
上載者:User

AOP:面向切面、面向方面、面向介面是一種橫切技術
橫切技術運用:
1.交易管理: (1)資料庫事務:(2)編程事務(3)聲明事物:Spring AOP-->聲明事物   
2.Tlog:
3.安全驗證: Spring AOP---OOP升級  
  

靜態代理原理:目標對象:調用商務邏輯    代理對象:日誌管理
展示層調用--->代理對象(日誌管理)-->調用目標對象

動態代理原理:spring AOP採用動態代理來實現
(1)實現InvocationHandler介面

(2)建立代理類(通過java API)

Proxy.newProxyInstance(動態載入代理類,代理類實現介面,使用handler);

(3)調用invoke方法(虛擬機器自動調用方法)

Tlog
 //調用目標對象
 method.invoke("目標對象","參數");
 Tlog

通過代理對象--(請求資訊)-->目標對象---(返回資訊)----> 代理對象

 

Spring 動態代理中的基本概念

1、關注點(concern)
   一個關注點可以是一個特定的問題,概念、或者應用程式的興趣點。總而言之,應用程式必須達到一個目標
   安全驗證、日誌記錄、交易管理都是一個關注點
   在oo應用程式中,關注點可能已經被代碼模組化了還可能散落在整個物件模型中
2、橫切關注點(crosscutting concern)
   如何一個關注點的實現代碼散落在多個類中或方法中
3、方面(aspect)
   一個方面是對一個橫切關注點模組化,它將那些原本散落在各處的,
   用於實現這個關注點的代碼規整在一處
4、建議(advice)通知
   advice是point cut執行代碼,是方面執行的具體實現
5、切入點(pointcut)
   用於指定某個建議用到何處
6、織入(weaving)
   將aspect(方面)運用到目標對象的過程
7、連接點(join point)
  程式執行過程中的一個點 

通知類型:
  try{
    //前置通知
         //環繞通知
            //調用目標對象方法
         //環繞通知
    //後置通知
  }catch(){
    //異常通知
  }finally{
    //終止通知
  }

 

流程圖

 

一.靜態代理原理執行個體:

項目結構圖:                                                                    

IUserServ介面代碼

public interface IUserServ {List<User> findAllUser();int deleteUserById(User user);int saveUser(User user);}


UserServImpl實作類別代碼

public class UserServImpl implements IUserServ {public int deleteUserById(User user) {System.out.println("******執行刪除方法******");return 0;}public List<User> findAllUser() {System.out.println("*******執行查詢方法*******");return null;}public int saveUser(User user) {System.out.println("*******執行添加方法********");return 0;}}

UserServProxyImpl實作類別代碼

//代理類:完成日誌輸出public class UserServProxyImpl implements IUserServ {// 訪問目標對象(UserServImpl)// 代理對象(UserServProxyImpl)// 建立目標對象private IUserServ iuserServ ;//= new UserServImpl();public UserServProxyImpl(IUserServ iuserServ){this.iuserServ = iuserServ;}public int deleteUserById(User user) {beforeLog();        //調用目標對象裡方法iuserServ.deleteUserById(user);afterLog();return 0;}public List<User> findAllUser() {beforeLog();//調用目標對象裡方法iuserServ.findAllUser();afterLog();return null;}public int saveUser(User user) {beforeLog();//調用目標對象裡方法iuserServ.saveUser(user);afterLog();return 0;}private void beforeLog() {System.out.println("開始執行");}private void afterLog() {System.out.println("執行完畢");}}

ActionTest測試類別代碼

public class ActionTest {public static void main(String[] args) {//使用者訪問代理對象---資訊->目標對象IUserServ iuserServ = new UserServProxyImpl(new UserServImpl());iuserServ.findAllUser();}}

運行結果:

開始執行
*******執行查詢方法*******
執行完畢
二.動態代理執行個體

項目結構圖:

IUserServ介面代碼與UserServImpl實作類別代碼和上述代碼相同

LogHandler類代碼

public class LogHandler implements InvocationHandler {//目標對象private Object targetObject;/** * 建立動態代理類 * @return object(代理類) */public Object createProxy(Object targetObject){this.targetObject = targetObject;return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(), targetObject.getClass().getInterfaces(), this);}@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {Object obj = null;try {beforeLog();//obj: 目標對象--->代理對象的傳回值--->返回給調用者的資訊//this.invoke("目標對象","代理對象給目標對象傳遞參數");//調用目標對象中方法obj = method.invoke(targetObject, args);afterLog();} catch (Exception e) {e.printStackTrace();}return obj;}//日誌管理方法private void beforeLog(){System.out.println("開始執行");}private void afterLog(){System.out.println("執行完畢");}}

ActionTest測試類別代碼:

public class ActionTest {public static void main(String[] args) {//建立代理對象iuserServLogHandler handler = new LogHandler();IUserServ iuserServ = (IUserServ)handler.createProxy(new UserServImpl());iuserServ.deleteUserById(new User());}}

運行結果:
開始執行
******執行刪除方法******
執行完畢
三.Spring AOP使用(2.x版本之前)

項目結構圖:



IUserServ介面代碼與UserServImpl實作類別代碼和上述代碼相同

配置步驟:

1、配置目標對象(applicationContext.xml)

<bean id="userServTarget" class="com.tarena.biz.impl.UserServImpl"/> 

 2、配置通知
(a)前置通知(BeforeLogAdvice)

public class BeforeLogAdvice implements MethodBeforeAdvice { /**    * Method method:調用目標對象的方法    * Object[] args:發送給目標對象的參數列表    * Object target:目標對象    */public void before(Method method, Object[] args, Object target)throws Throwable {beforeLog();}private void beforeLog(){System.out.println("開始執行");}}


(b)後置通知(AfterLogAdvice)

public class AfterLogAdvice implements AfterReturningAdvice {  /**    * Object returnValue:目標對象傳回值    *  Method method:目標對象方法名    *  Object[] args:目標對象參數列表    *  Object target:目標對象    */public void afterReturning(Object returnValue, Method method,Object[] args, Object target) throws Throwable {afterLog();}private void afterLog(){System.out.println("執行完畢");}}

       

(c)在spring容器中,讓容器管理通知(applicationContext.xml)

<!-- 定義通知 --><!-- 前置通知 --><bean id="beforeLogAdvice" class="com.tarena.advice.BeforeLogAdvice"/><!-- 後置通知 --><bean id="afterLogAdvice" class="com.tarena.advice.AfterLogAdvice"/>


3、配置代理對象(applicationContext.xml)  

<!-- 代理類作用: 組建代理程式類,織入通知 -->    <bean id="userServProxy"    class="org.springframework.aop.framework.ProxyFactoryBean">   <property name="interfaces">   <!-- 可以添加多個介面 -->    <list>     <value>com.tarena.biz.IUserServ</value>    </list>   </property>   <!-- 引入通知 -->   <property name="interceptorNames">    <list>     <value>beforeLogAdvice</value>     <value>afterLogAdvice</value>    </list>   </property>   <!-- 目標對象 -->   <property name="target" ref="userServTarget"/>  </bean>


 4.訪問()
Spring容器:通過代理對象調用-->織入通知--->目標對象
程式員:訪問代理對象   

測試類別(ActionTest):

public class ActionTest {public static void main(String[] args) {ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");IUserServ iuserServ = (IUserServ)ac.getBean("userServProxy");iuserServ.deleteUserById(new User());iuserServ.findAllUser();}}

運行結果:

開始執行
******執行刪除方法******
執行完畢
開始執行
*******執行查詢方法*******
執行完畢
四.Spring AOP使用(2.x版本之後)這種方式需要額外添加兩個jar包,

存放位置在spring-framework-2.5.6.SEC01\lib\aspectj檔案夾下。

項目結構圖


IUserServ介面代碼與UserServImpl實作類別代碼和上述代碼相同

LogAdvice中

public class LogAdvice {public void beforeLog(){System.out.println("開始執行");}public void afterLog(){System.out.println("執行完畢");}}

applicationContext.xml中

<!-- spring2.x後 --><!-- 目標對象 --><bean id="userServImpl" class="com.tarena.biz.impl.UserServImpl"/><!-- 通知 --><bean id="logAdvice" class="com.tarena.advice.LogAdvice"/><aop:config><aop:aspect id="logAspect" ref="logAdvice"><!-- 切入點 --><aop:pointcut id="beforePointCut"     expression="execution(* saveUser*(..))"/>    <aop:pointcut id="afterPointCut"     expression="execution(* saveUser*(..))"/><!-- 織入(通知作用於切入點) --><aop:before method="beforeLog" pointcut-ref="beforePointCut"/><aop:after method="afterLog" pointcut-ref="afterPointCut"/></aop:aspect></aop:config>

測試類別:

public class ActionTest {public static void main(String[] args) {ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");IUserServ iuserServ = (IUserServ)ac.getBean("userServImpl");iuserServ.deleteUserById(new User());iuserServ.findAllUser();iuserServ.saveUser(new User());}}

運行結果
******執行刪除方法******
*******執行查詢方法*******
開始執行
*******執行添加方法********
執行完畢

注:如果要在業務層所有的方法前後添加記錄檔,則需要更改為以下配置

<aop:pointcut id="beforePointCut"     expression="execution(* com.tarena.biz.*.*(..))"/>    <aop:pointcut id="afterPointCut"     expression="execution(* com.tarena.biz.*.*(..))"/>


運行結果:

開始執行
******執行刪除方法******
執行完畢
開始執行
*******執行查詢方法*******
執行完畢
開始執行
*******執行添加方法********
執行完畢


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.