Spring AOP 即 Aspect-oriented programming,面向切面編程,是作為面向對象編程的一種補充,專門用於處理系統中分布於各個模塊(不同方法)中的交叉關注點的問題。簡單地說,就是一個攔截器( interceptor )攔截一些處理過程。
例如,當一 個method 被執行,Spring AOP 能夠劫持正在運行的 method ,在 method 執行前或者后加入一些額外的功能。
在 Spring AOP 中,支持 4 種類型的通知( Advice ):
- Before advice - method 執行前通知
- After returning advice - method 返回一個結果后通知
- After throwing advice - method 拋出異常后通知
- Around advice - 環繞通知,結合了以上三種
下邊這個例子解釋 Spring AOP 怎樣工作。首先一個簡單的不使用 AOP 的例子。先創建一個簡單的 Service ,為了稍后演示,這個類中加了幾個簡單的打印 method 。
1.pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.shiyanlou.spring</groupId> <artifactId>aop</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>aop</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.0.RELEASE</version> </dependency> </dependencies> </project>
2.CustomerService.java
package com.shiyanlou.spring.aop; public class CustomerService { private String name; private String url; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public void printName(){ System.out.println("Customer name:"+this.name); } public void printUrl(){ System.out.println("Customer url:"+this.url); } public void printThrowException() { throw new IllegalArgumentException(); } }
3.SrpingAOP.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="customerService" class="com.shiyanlou.spring.aop.CustomerService"> <property name="name" value="zoey"/> <property name="url" value="http://shiyanlou.com"/> </bean> </beans>
4.App.java
package com.shiyanlou.spring.aop; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main( String[] args ) { ApplicationContext appContext = new ClassPathXmlApplicationContext( new String[]{"SpringAOP.xml"}); CustomerService cust = (CustomerService)appContext.getBean("customerService"); System.out.println("*************************"); cust.printName(); System.out.println("*************************"); cust.printUrl(); System.out.println("*************************"); try { cust.printThrowException(); } catch (Exception e) { } } }
4 種類型的通知( Advice )
1.Before Advice
method 運行前,將運行下面的代碼
HijackBeforeMethod.java 如下:
package com.shiyanlou.spring.aop; import java.lang.reflect.Method; import org.springframework.aop.MethodBeforeAdvice; public class HijackBeforeMethod implements MethodBeforeAdvice{ public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable { System.out.println("HijackBeforeMethod : Before method hijacked!"); } }
在配置文件中加入新的 bean 配置 HijackBeforeMethod ,然后創建一個新的代理( proxy ),命名為 customerServiceProxy 。target
定義你想劫持哪個 bean; interceptorNames
定義想用哪個 class ( advice )劫持 target 。 ApringAOP.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="customerService" class="com.shiyanlou.spring.aop.CustomerService"> <property name="name" value="zoey"/> <property name="url" value="http://shiyanlou.com"/> </bean> <bean id="hijackBeforeMethodBean" class="com.shiyanlou.spring.aop.HijackBeforeMethod"/> <bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target" ref="customerService"/> <property name="interceptorNames"> <list> <value>hijackBeforeMethodBean</value> </list> </property> </bean> </beans>
用 Spring proxy 之前,必須添加 CGLIB2 類庫,,以下是 pom.xml 依賴:
<dependency> <groupId>org.glassfish.hk2.external</groupId> <artifactId>cglib</artifactId> <version>2.2.0-b23</version> </dependency>
app.java
package com.shiyanlou.spring.aop; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main( String[] args ) { ApplicationContext appContext = new ClassPathXmlApplicationContext( new String[]{"SpringAOP.xml"}); CustomerService cust = (CustomerService)appContext.getBean("customerServiceProxy"); System.out.println("*************************"); cust.printName(); System.out.println("*************************"); cust.printUrl(); System.out.println("*************************"); try { cust.printThrowException(); } catch (Exception e) { } } }
運行結果:
每一個 customerService 的 method 運行前,都將先執行 HijackBeforeMethod 的 before 方法。
2 After Returning Advice
創建一個實現了接口 AfterReturningAdvice 的 class ,method 運行后,直到返回結果后,才運行下邊的代碼,如果沒有返回結果,將不運行切入的代碼。
HijackAfterMethod.java 如下:
package com.shiyanlou.spring.aop; import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; public class HijackAfterMethod implements AfterReturningAdvice { public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable { System.out.println("After method hijack"); } }
SpringAOP.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="customerService" class="com.shiyanlou.spring.aop.CustomerService"> <property name="name" value="zoey"/> <property name="url" value="http://shiyanlou.com"/> </bean> <bean id="hijackBeforeMethodBean" class="com.shiyanlou.spring.aop.HijackBeforeMethod"/> <bean id="hijackAfterMethodBean" class="com.shiyanlou.spring.aop.HijackAfterMethod"/> <bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target" ref="customerService"/> <property name="interceptorNames"> <list> <value>hijackAfterMethodBean</value> </list> </property> </bean> </beans>
App.java
package com.shiyanlou.spring.aop; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main( String[] args ) { ApplicationContext appContext = new ClassPathXmlApplicationContext( new String[]{"SpringAOP.xml"}); CustomerService cust = (CustomerService)appContext.getBean("customerServiceProxy"); System.out.println("*************************"); cust.printName(); System.out.println("*************************"); cust.printUrl(); System.out.println("*************************"); try { cust.printThrowException(); } catch (Exception e) { } } }
運行結果:
3 Afetr Throwing Advice
創建一個實現了 ThrowsAdvice 接口的 class ,劫持 IllegalArgumentException 異常,目標 method 運行時,拋出 IllegalArgumentException 異常后,運行切入的方法。HijackThrowException.java 如下:
package com.shiyanlou.spring.aop; import org.springframework.aop.ThrowsAdvice; public class HijackThrowException implements ThrowsAdvice { public void afterThrowing(IllegalArgumentException e) throws Throwable { System.out.println("HijackThrowException : Throw exception hijacked!"); } }
修改 bean 配置文件,加入了 hijackThrowExceptionBean ,ApringAdvice.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="customerService" class="com.shiyanlou.spring.aop.CustomerService"> <property name="name" value="zoey"/> <property name="url" value="http://shiyanlou.com"/> </bean> <bean id="hijackBeforeMethodBean" class="com.shiyanlou.spring.aop.HijackBeforeMethod"/> <bean id="hijackAfterMethodBean" class="com.shiyanlou.spring.aop.HijackAfterMethod"/> <bean id="hijackThrowExceptionBean" class="com.shiyanlou.spring.aop.HijackThrowException"/> <bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target" ref="customerService"/> <property name="interceptorNames"> <list> <value>hijackThrowExceptionBean</value> </list> </property> </bean> </beans>
運行結果:
4 Around Advice
結合了以上 3 種形式的 Advice ,創建一個實現了接口 MethodInterceptor 的 class ,你必須通過 methodInvocation.proceed() 來調用原來的方法,即通過調用 methodInvocation.proceed() 來調用 CustomerService 中的每一個方法,當然也可以不調用原方法 HijackAroundMethod.java 如下
package com.shiyanlou.spring.aop; import java.lang.reflect.Method; import java.util.Arrays; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; public class HijackAroundMethod implements MethodInterceptor { public Object invoke(MethodInvocation methodInvocation) throws Throwable { System.out.println("Method name : " + methodInvocation.getMethod().getName()); System.out.println("Method arguments : " + Arrays.toString(methodInvocation.getArguments())); // 相當於 MethodBeforeAdvice System.out.println("HijackAroundMethod : Before method hijacked!"); try { // 調用原方法,即調用CustomerService中的方法 Object result = methodInvocation.proceed(); // 相當於 AfterReturningAdvice System.out.println("HijackAroundMethod : After method hijacked!"); return result; } catch (IllegalArgumentException e) { // 相當於 ThrowsAdvice System.out.println("HijackAroundMethod : Throw exception hijacked!"); throw e; } } }
修改 bean 配置文件,加入了 hijackAroundMethodBean ,ApringAOP.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="customerService" class="com.shiyanlou.spring.aop.CustomerService"> <property name="name" value="zoey"/> <property name="url" value="http://shiyanlou.com"/> </bean> <bean id="hijackBeforeMethodBean" class="com.shiyanlou.spring.aop.HijackBeforeMethod"/> <bean id="hijackAfterMethodBean" class="com.shiyanlou.spring.aop.HijackAfterMethod"/> <bean id="hijackThrowExceptionBean" class="com.shiyanlou.spring.aop.HijackThrowException"/> <bean id="hijackAroundMethodBean" class="com.shiyanlou.spring.aop.HijackAroundMethod" /> <bean id="customerServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target" ref="customerService"/> <property name="interceptorNames"> <list> <value>hijackAroundMethodBean</value> </list> </property> </bean> </beans>
運行app.java結果:
CustomerService 中每一個方法的調用,都會執行 HijackAroundMethod 中的 invoke 方法,可以看到整個切入點將目標 around 。
大多數的 Spring 開發者只用 Around Advice ,因為它能夠實現所有類型的 Advice 。
在實際的項目開發中,我們還是要盡量選擇適合的 Advice 。
在以上的例子中,CustomerService 中的所有方法都被自動攔截,但是大多數情況下,我們不需要攔截一個 class 中的所有方法,而是攔截符合條件的方法。
這時,我們就需要用到 Pointcut and Advice ,即切入點和通知