什么是AOP(aspect Oriented Programming):
我們一直把OOP(Object Oriented Programming)面向對象的編程稱之為縱向編程方式,它以一條線的方式向終點延伸,可以想象成一條條綿延無盡的道路。而往往會出現一種情況:許多不同的路會交織在一起,這就是所謂的不同的對象之間會有存在相同的處理邏輯。為了使這部分邏輯能夠得到重用,更好的理解,更方便的維護,就出現了AOP(Aspect Oriented Programming)面向方面的編程思想,稱之為橫向編程方式。
怎么實現AOP:
AOP編程思想是通過代理技術來實現的,這個可以參考設計模式,然后研究一下java動態代理技術來了解。
在Spring中有兩種方式實現代理:
1.JDK動態代理:其代理對象必須是某個接口的實現,它是通過在運行期間創建一個接口的實現類來完成對目標對象的代理的。
2.CHLIB代理:實現原理類似于JDK動態代理,只是它在運行期間生成的代理對象是針對目標類擴展的子類,DGLIB是高效的代碼生成包,底層是依賴ASM操作字節碼實現的,性能比JDK強。但是對于類中final的方法和類無法代理。(需要將CGLIB二進制發行包放到classpath下面)。
下面我們將實現一個簡單的例子:
//java代碼@Aspectpublic class AspectJTest {@Pointcut("execution(* *.test(..))")public void test(){System.out.println("test");}@Before("test()")public void beforeTest(){System.out.println("before");}@After("test()")public void afterTest(){System.out.println("111");object=null;try {o = p.proceed();} catch (Exception e) {e.printStackTrace();}System.out.println("2222");}@Around("test()")public void aroundTest(ProceedingJoinPoint p){System.out.println("");}}//配置文件<?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: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/aop http://www.springframework.org/schema/beans/spring-aop-3.0.xsd"> <!-- 啟動對@AspectJ注解的支持 --> <aop:aspectj-autoproxy/></beans>
實現AOP的代理的代理原則:
如果目標對象實現了接口,默認情況下采用JDK的動態代理實現AOP。
如果目標對象實現了接口,可以強制其使用CGLIB實現AOP可是在配置文件中加入<aop:aspectj-autoproxy proxy-target-class="true">。
如果慕白哦對象沒有實現接口,必須采用CGLIB庫,Spring會自動在JDK代理和CGLIB之間轉換。
新聞熱點
疑難解答