參考:
1. http://www.cnblogs.com/hongwz/p/5764917.html
2. https://www.cnblogs.com/zhaozihan/p/5953063.html (非常棒)
一.前言
在以前的項目中,很少去關注spring aop的具體實現與理論,只是簡單瞭解了一下什麼是aop具體怎麼用,看到了一篇博文寫得還不錯,就轉載來學習一下,博文地址:http://www.cnblogs.com/xrq730/p/4919025.html
AOP
AOP(Aspect Oriented Programming),即面向切面編程,可以說是OOP(Object Oriented Programming,面向對象編程)的補充和完善。OOP引入封裝、繼承、多態等概念來建立一種對象層次結構,用於模擬公共行爲的一個集合。不過OOP允許開發者定義縱向的關係,但並不適合定義橫向的關係,例如日誌功能。日誌代碼往往橫向地散佈在所有對象層次中,而與它對應的對象的核心功能毫無關係對於其他類型的代碼,如安全性、異常處理和透明的持續性也都是如此,這種散佈在各處的無關的代碼被稱爲橫切(cross cutting),在OOP設計中,它導致了大量代碼的重複,而不利於各個模塊的重用。
AOP技術恰恰相反,它利用一種稱爲"橫切"的技術,剖解開封裝的對象內部,並將那些影響了多個類的公共行爲封裝到一個可重用模塊,並將其命名爲"Aspect",即切面。所謂"切面",簡單說就是那些與業務無關,卻爲業務模塊所共同調用的邏輯或責任封裝起來,便於減少系統的重複代碼,降低模塊之間的耦合度,並有利於未來的可操作性和可維護性。
使用"橫切"技術,AOP把軟件系統分爲兩個部分:核心關注點和橫切關注點。業務處理的主要流程是核心關注點,與之關係不大的部分是橫切關注點。橫切關注點的一個特點是,他們經常發生在覈心關注點的多處,而各處基本相似,比如權限認證、日誌、事物。AOP的作用在於分離系統中的各種關注點,將核心關注點和橫切關注點分離開來。
AOP核心概念
1、橫切關注點
對哪些方法進行攔截,攔截後怎麼處理,這些關注點稱之爲橫切關注點
2、切面(aspect)
類是對物體特徵的抽象,切面就是對橫切關注點的抽象
3、連接點(joinpoint)
被攔截到的點,因爲Spring只支持方法類型的連接點,所以在Spring中連接點指的就是被攔截到的方法,實際上連接點還可以是字段或者構造器
4、切入點(pointcut)
對連接點進行攔截的定義。連接點是實的感念,切入點是虛的概念。連接點可能是某個具體方法的調用,而切入點往往對應着一組連接點,在Spring運行期間,AOP正是通過分析切入點這個虛的概念,找到旗下所有匹配的連接點,再把通知進行織入到具體方法當中。
5、通知(advice)
所謂通知指的就是指攔截到連接點之後要執行的代碼,通知分爲前置、後置、異常、最終、環繞通知五類
6、目標對象
代理的目標對象
7、織入(weave)
將切面應用到目標對象並導致代理對象創建的過程
8、引入(introduction)
在不修改代碼的前提下,引入可以在運行期爲類動態地添加一些 方法或字段
Spring對AOP的支持
Spring中AOP代理由Spring的IOC容器負責生成、管理,其依賴關係也由IOC容器負責管理。因此,AOP代理可以直接使用容器中的其它bean實例作爲目標,這種關係可由IOC容器的依賴注入提供。Spring創建代理的規則爲:
1、默認使用Java動態代理來創建AOP代理,這樣就可以爲任何接口實例創建代理了
2、當需要代理的類不是代理接口的時候,Spring會切換爲使用CGLIB代理,也可強制使用CGLIB
AOP編程其實是很簡單的事情,縱觀AOP編程,程序員只需要參與三個部分:
1、定義普通業務組件
2、定義切入點,一個切入點可能橫切多個業務組件
3、定義增強處理,增強處理就是在AOP框架中爲普通業務組件織入的處理動作
所以進行AOP編程的關鍵就是定義切入點和定義增強處理,一旦定義了合適的切入點和增強處理,AOP框架將自動生成AOP代理,即:代理對象的方法=增強處理+被代理對象的方法。
下面給出一個Spring AOP的.xml文件模板,名字叫做aop.xml,之後的內容都在aop.xml上進行擴展:
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
</beans>
基於Spring的AOP簡單實現
注意一下,在講解之前,說明一點:使用Spring AOP,要成功運行起代碼,只用Spring提供給開發者的jar包是不夠的,請額外上網下載兩個jar包:
1、aopalliance.jar
2、aspectjweaver.jar
若使用Spring boot,請按照如下配置:
<!-- AOP -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
開始講解用Spring AOP的XML實現方式,先定義一個接口:
public interface HelloWorld
{
void printHelloWorld();
void doPrint();
}
定義兩個接口實現類:
public class HelloWorldImpl1 implements HelloWorld
{
public void printHelloWorld()
{
System.out.println("Enter HelloWorldImpl1.printHelloWorld()");
}
public void doPrint()
{
System.out.println("Enter HelloWorldImpl1.doPrint()");
return ;
}
}
public class HelloWorldImpl2 implements HelloWorld
{
public void printHelloWorld()
{
System.out.println("Enter HelloWorldImpl2.printHelloWorld()");
}
public void doPrint()
{
System.out.println("Enter HelloWorldImpl2.doPrint()");
return ;
}
}
橫切關注點,這裏是打印時間:
public class TimeHandler {
public void printStartTime(){
System.out.println("前置增強 StartTime ---> " + System.currentTimeMillis());
}
public void printEndTime(){
System.out.println("後置增強 EndTime ---> " + System.currentTimeMillis());
}
}
有這三個類就可以實現一個簡單的Spring AOP了,看一下aop.xml的配置:
<?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-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
<!-- 將以下三個類放入Spring容器中,交由IOC管理 -->
<bean id="timeHandler" class="com.learn.learning.aop.example1.TimeHandler" />
<bean id="helloWorldImpl1" class="com.learn.learning.aop.example1.HelloWorldImpl1"/>
<bean id="helloWorldImpl2" class="com.learn.learning.aop.example1.HelloWorldImpl2"/>
<aop:config>
<!-- 首先定義切面,餘下所有的配置都是圍繞切面展開 -->
<aop:aspect id="time" ref="timeHandler">
<!-- ponitcut:切入點
(..)代表所有參數,(*)代表一個參數, (*, String)代表第二個參數
返回值 路徑 參數
expression: example1包下任意子包中的任意類中的包含hello的所有方法,參數任意
-->
<aop:pointcut id="addAllMethod" expression="execution(* com.learn.learning.aop.example1.HelloWorld.*Hello*(..))" />
<aop:before method="printStartTime" pointcut-ref="addAllMethod" />
<aop:after method="printEndTime" pointcut-ref="addAllMethod" />
</aop:aspect>
</aop:config>
</beans>
寫一個main函數調用一下:
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("/config/example1/aop.xml");
HelloWorld helloWorldImpl1 = (HelloWorld)context.getBean("helloWorldImpl1");
helloWorldImpl1.printHelloWorld();
System.out.println("--------------分割線--------------");
helloWorldImpl1.doPrint();
}
注意: 此處可能出現如下錯誤,錯誤原因在於創建代理失敗,一般是因爲aspect jweaver版本不對或是沒有引入導致。
exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'timeHandler' defined in class path resource [config/example1/aop.xml]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.aspectj.AspectJPointcutAdvisor#0': Cannot create inner bean '(inner bean)#4690b489' of type [org.springframework.aop.aspectj.AspectJMethodBeforeAdvice] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#4690b489': Cannot resolve reference to bean 'addAllMethod' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'addAllMethod': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.aop.aspectj.AspectJExpressionPointcut]: No default constructor found; nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldException
main函數執行結果如下:
前置增強 StartTime ---> 1544951972828
Enter HelloWorldImpl1.printHelloWorld()
後置增強 EndTime ---> 1544951972828
--------------分割線--------------
Enter HelloWorldImpl1.doPrint()
不難發現,我們給實現了HelloWorld接口的所有類中,包含Hello字符串的所有方法都加上了代理。例1中,helloWorldImpl1是代理對象,printHelloWorld()是被代理對象的方法,而printStartTime()和printEndTime()則是增強處理。
所以讓我們再複習一遍,代理對象的方法=增強處理+被代理對象的方法。
代理
1. 靜態代理
靜態代理產生於代碼編譯階段,即一旦代碼編輯後就無法發生改變了。
定義接口:
public interface IPerson {
void doSomething();
}
定義實現類:
public class PersonImpl implements IPerson{
@Override
public void doSomething() {
System.out.println("我要買apple");
}
}
定義靜態代理:
public class PersonStaticProxy {
private IPerson iPerson;
public PersonStaticProxy(IPerson iPerson){
this.iPerson = iPerson;
}
public void doSomething(){
System.out.println("before proxy");
iPerson.doSomething();
System.out.println("after proxy");
}
public static void main(String[] args) {
PersonStaticProxy personStaticProxy = new PersonStaticProxy(new PersonImpl());
personStaticProxy.doSomething();
}
}
輸出:
before proxy
我要買apple
after proxy
通過代理類我們實現了將日誌代碼集成到了目標類,但從上面我們可以看出它具有很大的侷限性:需要固定的類(PersonStaticProxy)編寫接口,需要實現接口中被代理的每一個方法(畢竟以後是拿着PersonStaticProxy代替PersonImpl來使用,因此必須實現PersonImpl中的公用方法),如果有多個類需要加入日誌代碼,還需要些多個代理類,這就造成了大量的代碼重複。
2. 動態代理
那能否通過一次代碼編寫就將logger織入到所有的函數中呢?答案是可以的。
public class PersonDynamicProxy implements InvocationHandler {
private Object delegate;
public Object bind(Object delegate){
this.delegate = delegate;
Class[] interfaces = delegate.getClass().getInterfaces();//實現的所有接口
return Proxy.newProxyInstance(delegate.getClass().getClassLoader(), interfaces, this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
try{
System.out.println("Before Proxy");
method.invoke(delegate, args);
System.out.println("After Proxy");
}catch(Exception e){
throw e;
}
return result;
}
public static void main(String[] args) {
PersonDynamicProxy personDynamicProxy = new PersonDynamicProxy();
IPerson iPerson = (IPerson) personDynamicProxy.bind(new PersonImpl());
Objects.requireNonNull(iPerson);
iPerson.doSomething();
System.out.println("--------------分割線--------------");
iPerson.saySomething();
}
}
注意觀察Proxy.newProxyInstance() 創建代理類對象方法。
3. CGLIB
CGLIB解決了動態代理的難題,它通過生成目標類子類的方式來實現來實現代理,而不是接口,規避了接口的侷限性。CGLIB是一個強大的高性能代碼生成包(生成原理還沒研究過),其在運行時期(非編譯時期)生成被 代理對象的子類,並重寫了被代理對象的所有方法,從而作爲代理對象。
public class PersonCGLIBProxy implements MethodInterceptor {
private Object delegate;
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
System.out.println("Before proxy");
Object result = methodProxy.invokeSuper(method, args);
System.out.println("After proxy");
return result;
}
public static PersonImpl getProxyInstance() {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(PersonImpl.class);
enhancer.setCallback(new PersonCGLIBProxy());
return (PersonImpl)enhancer.create();
}
public static void main(String[] args) {
PersonImpl pp = PersonCGLIBProxy.getProxyInstance();
pp.doSomething();
}
}
但很遺憾這裏報錯了,希望以後能解決:
Before proxy
Exception in thread "main" java.lang.ClassCastException: java.lang.reflect.Method cannot be cast to com.learn.learning.aop.example3.PersonImpl$$EnhancerByCGLIB$$b2083a72
at com.learn.learning.aop.example3.PersonImpl$$EnhancerByCGLIB$$b2083a72$$FastClassByCGLIB$$57108bb2.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at com.learn.learning.aop.example3.PersonCGLIBProxy.intercept(PersonCGLIBProxy.java:24)
at com.learn.learning.aop.example3.PersonImpl$$EnhancerByCGLIB$$b2083a72.doSomething(<generated>)
at com.learn.learning.aop.example3.PersonCGLIBProxy.main(PersonCGLIBProxy.java:39)
而且CGLIB也具有侷限性,對於無法生成子類的類(final類),肯定是沒有辦法生成代理子類的。
基於Spring的AOP使用其他細節
1. 多個橫切關注點同時存在
打印日誌,Java類爲:
public class LogHandler
{
public void LogBefore()
{
System.out.println("Log before method");
}
public void LogAfter()
{
System.out.println("Log after method");
}
}
aop.xml配置爲:
<?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-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
<!-- 將以下三個類放入Spring容器中,交由IOC管理 -->
<bean id="timeHandler" class="com.learn.learning.aop.example1.TimeHandler" />
<!-- 新增日誌橫切關注點 -->
<bean id="logHandler" class="com.learn.learning.aop.example2.LogHandler"/>
<bean id="helloWorldImpl1" class="com.learn.learning.aop.example1.HelloWorldImpl1"/>
<bean id="helloWorldImpl2" class="com.learn.learning.aop.example1.HelloWorldImpl2"/>
<aop:config>
<!-- 首先定義切面,餘下所有的配置都是圍繞切面展開 -->
<aop:aspect id="time" ref="timeHandler" order="2">
<!-- ponitcut:切入點
(..)代表所有參數,(*)代表一個參數, (*, String)代表第二個參數
返回值 路徑 參數
expression: example1包下任意子包中的任意類中的包含hello的所有方法,參數任意
-->
<aop:pointcut id="addAllMethod" expression="execution(* com.learn.learning.aop.example1.HelloWorld.*Hello*(..))" />
<aop:before method="printStartTime" pointcut-ref="addAllMethod" />
<aop:after method="printEndTime" pointcut-ref="addAllMethod" />
</aop:aspect>
<!-- 定義第二個切面 -->
<aop:aspect id="log" ref="logHandler" order="1">
<aop:pointcut id="printLog" expression="execution(* com.learn.learning.aop.example1.HelloWorld.*Hello*(..))" />
<aop:before method="LogBefore" pointcut-ref="printLog"/>
<aop:after method="LogAfter" pointcut-ref="printLog"/>
</aop:aspect>
</aop:config>
</beans>
main函數輸出結果:
Log before method
前置增強 StartTime ---> 1544953402763
Enter HelloWorldImpl1.printHelloWorld()
後置增強 EndTime ---> 1544953402763
Log after method
--------------分割線--------------
Enter HelloWorldImpl1.doPrint()
若在aop.xml中定義了多個切面,切面按以下兩種情況執行:
1. spring 默認按照aspect的定義順序執行。
2. aspect提供了order屬性,數字越小,權重越大。