本文也同步發佈至簡書,地址: https://www.jianshu.com/p/f70...
AOP設計模式一般運用在日誌,校驗等業務場景,本文將簡單介紹基於Spring的AOP代理模式的運用。html
代理(Proxy)是一種提供了對目標對象另外的訪問方式,即經過代理對象訪問目標對象。這樣作的好處是:能夠在目標對象實現的基礎上,加強額外的功能操做,即擴展目標對象的功能。
這裏使用到編程中的一個思想:不要隨意去修改別人已經寫好的代碼或者方法,若是需改修改,能夠經過代理的方式來擴展該方法。java
靜態代理在使用時,須要定義接口或者父類,被代理對象與代理對象一塊兒實現相同的接口或者是繼承相同父類。git
JDK動態代理有如下特色:
1.代理對象,不須要實現接口
2.代理對象的生成,是利用JDK的API,動態的在內存中構建代理對象(須要咱們指定建立代理對象/目標對象實現的接口的類型)
3.動態代理也叫作:JDK代理,接口代理github
Cglib代理,也叫做子類代理,它是在內存中構建一個子類對象從而實現對目標對象功能的擴展。spring
AOP實現的關鍵在於AOP框架自動建立的AOP代理,AOP代理主要分爲靜態代理和動態代理,靜態代理的表明爲AspectJ;而動態代理則以Spring AOP爲表明。本文以Spring AOP的實現進行分析和介紹。express
Spring AOP使用的動態代理,所謂的動態代理就是說AOP框架不會去修改字節碼,而是在內存中臨時爲方法生成一個AOP對象,這個AOP對象包含了目標對象的所有方法,而且在特定的切點作了加強處理,並回調原對象的方法。編程
Spring AOP中的動態代理主要有兩種方式,JDK動態代理
和CGLIB動態代理
。JDK動態代理經過反射來接收被代理的類,而且要求被代理的類必須實現一個接口。JDK動態代理的核心是InvocationHandler
接口和Proxy
類。設計模式
若是目標類沒有實現接口,那麼Spring AOP會選擇使用CGLIB來動態代理目標類。CGLIB(Code Generation Library),是一個代碼生成的類庫,能夠在運行時動態的生成某個類的子類,注意,CGLIB是經過繼承的方式作的動態代理,所以若是某個類被標記爲final
,那麼它是沒法使用CGLIB作動態代理的。框架
注意:以上片斷引用自文章 Spring AOP的實現原理,若有冒犯,請聯繫筆者刪除之,謝謝!
Spring AOP判斷是JDK代理仍是CGLib代理的源碼以下(來自org.springframework.aop.framework.DefaultAopProxyFactory
):ide
@Override public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException { if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) { Class<?> targetClass = config.getTargetClass(); if (targetClass == null) { throw new AopConfigException("TargetSource cannot determine target class: " + "Either an interface or a target is required for proxy creation."); } if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) { return new JdkDynamicAopProxy(config); } return new ObjenesisCglibAopProxy(config); } else { return new JdkDynamicAopProxy(config); } }
由代碼發現,若是配置proxyTargetClass = true
了而且目標類非接口的狀況,則會使用CGLib代理,不然使用JDK代理。
Spring AOP的配置有兩種方式,XML和註解方式。
首先須要引入AOP相關的DTD配置,以下:
<beans xmlns="http://www.springframework.org/schema/beans" 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.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd ">
而後須要引入AOP自動代理配置:
<!-- 自動掃描(自動注入) --> <context:component-scan base-package="org.landy" /> <!-- 指定proxy-target-class爲true可強制使用cglib --> <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
Java配置類以下:
/** * 至關於Spring.xml配置文件的做用 * @author landyl * @create 2:44 PM 09/30/2018 */ @Configuration //@EnableLoadTimeWeaving(aspectjWeaving = EnableLoadTimeWeaving.AspectJWeaving.ENABLED) @EnableAspectJAutoProxy(proxyTargetClass = true) //@EnableAspectJAutoProxy @ComponentScan(basePackages = "org.landy") public class ApplicationConfigure { @Bean public ApplicationUtil getApplicationUtil() { return new ApplicationUtil(); } }
須要使用Spring AOP須要引入如下Jar包:
<properties> <spring.version>5.0.8.RELEASE</spring.version> <aspectj.version>1.8.7</aspectj.version> </properties> <!-- aspectjrt.jar包主要是提供運行時的一些註解,靜態方法等等東西,一般咱們要使用aspectJ的時候都要使用這個包。 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${aspectj.version}</version> </dependency> <!-- aspectjweaverjar包主要是提供了一個java agent用於在類加載期間織入切面(Load time weaving)。 而且提供了對切面語法的相關處理等基礎方法,供ajc使用或者供第三方開發使用。這個包通常咱們不須要顯式引用,除非須要使用LTW。 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${aspectj.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> <scope>compile</scope> </dependency>
以上兩種配置方式,單元測試須要注意一個地方就是引入配置的方式不同,區別以下:
XML方式
@ContextConfiguration(locations = { "classpath:spring.xml" }) //加載配置文件 @RunWith(SpringJUnit4ClassRunner.class) //使用junit4進行測試 public class SpringTestBase extends AbstractJUnit4SpringContextTests { }
@ContextConfiguration(classes = ApplicationConfigure.class) @RunWith(SpringJUnit4ClassRunner.class) //使用junit4進行測試 public class SpringTestBase extends AbstractJUnit4SpringContextTests { }
配置好了之後,之後全部的測試類都繼承SpringTestBase
類便可。
本文將以校驗某個業務邏輯爲例說明Spring AOP代理模式的運用。
按照慣例,仍是以客戶信息更新校驗爲例,假設有個校驗類以下:
/** * @author landyl * @create 2:22 PM 09/30/2018 */ @Component public class CustomerUpdateRule implements UpdateRule { //利用自定義註解,進行AOP切面編程,進行其餘業務邏輯的校驗操做 @StatusCheck public CheckResult check(String updateStatus, String currentStatus) { System.out.println("CustomerUpdateRule:在此還有其餘業務校驗邏輯。。。。"+updateStatus + "____" + currentStatus); return new CheckResult(); } }
此時咱們須要定義一個註解StatusCheck
類,以下:
/** * @author landyl * @create 2:37 PM 09/23/2018 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface StatusCheck { }
此註解僅爲一個標記註解。最爲主要的就是定義一個更新校驗的切面類,定義好切入點。
@Component @Aspect public class StatusCheckAspect { private static final int VALID_UPDATE = Constants.UPDATE_STATUS_VALID_UPDATE; private static final Logger LOGGER = LoggerFactory.getLogger(StatusCheckAspect.class); //定義切入點:定義一個方法,用於聲明切面表達式,通常地,該方法中再也不須要添加其餘的代碼 @Pointcut("execution(* org.landy.business.rules..*(..)) && @annotation(org.landy.business.rules.annotation.StatusCheck)") public void declareJoinPointExpression() {} /** * 前置通知 * @param joinPoint */ @Before("declareJoinPointExpression()") public void beforeCheck(JoinPoint joinPoint) { System.out.println("before statusCheck method start ..."); System.out.println(joinPoint.getSignature()); //得到自定義註解的參數 String methodName = joinPoint.getSignature().getName(); List<Object> args = Arrays.asList(joinPoint.getArgs()); System.out.println("The method " + methodName + " begins with " + args); System.out.println("before statusCheck method end ..."); } }
具體代碼請參見github。
JDK動態代理必須實現一個接口,本文實現UpdateRule
爲例,
public interface UpdateRule { CheckResult check(String updateStatus, String currentStatus); }
而且AOP須要作以下配置:
XML方式:
<!-- 指定proxy-target-class爲true可強制使用cglib --> <aop:aspectj-autoproxy proxy-target-class="false"></aop:aspectj-autoproxy>
註解方式:
@Configuration @EnableAspectJAutoProxy @ComponentScan(basePackages = "org.landy") public class ApplicationConfigure { }
在測試類中,必須使用接口方式注入:
/** * @author landyl * @create 2:32 PM 09/30/2018 */ public class CustomerUpdateRuleTest extends SpringTestBase { @Autowired private UpdateRule customerUpdateRule; //JDK代理方式必須以接口方式注入 @Test public void customerCheckTest() { System.out.println("proxy class:" + customerUpdateRule.getClass()); CheckResult checkResult = customerUpdateRule.check("2","currentStatus"); AssertUtil.assertTrue(checkResult.getCheckResult() == 0,"與預期結果不一致"); } }
測試結果以下:
proxy class:class com.sun.proxy.$Proxy34 2018-10-05 14:18:17.515 [main] INFO org.landy.business.rules.aop.StatusCheckAspect - Status check around method start .... before statusCheck method start ... CheckResult org.landy.business.rules.stategy.UpdateRule.check(String,String) The method check begins with [2, currentStatus] before statusCheck method end ... CustomerUpdateRule:在此還有其餘業務校驗邏輯。。。。2____currentStatus 2018-10-05 14:18:17.526 [main] INFO org.landy.business.rules.aop.StatusCheckAspect - execute the target method,the return result_msg:null 2018-10-05 14:18:17.526 [main] INFO org.landy.business.rules.aop.StatusCheckAspect - Status check around method end ....
以上結果說明它生成的代理類爲$Proxy34,說明是JDK代理。
使用CGlib能夠不用接口(經測試,用了接口好像也沒問題)。在測試類中,必須使用實現類方式注入:
@Autowired private CustomerUpdateRule customerUpdateRule;
而且AOP須要作以下配置:
XML方式:
<!-- 指定proxy-target-class爲true可強制使用cglib --> <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
註解方式:
@Configuration @EnableAspectJAutoProxy(proxyTargetClass = true) @ComponentScan(basePackages = "org.landy") public class ApplicationConfigure { }
不過發現我並未配置proxyTargetClass = true
也能夠正常運行,有點奇怪。(按理說,默認是爲false)
運行結果生成的代理類爲:
proxy class:class org.landy.business.rules.stategy.CustomerUpdateRule$$EnhancerBySpringCGLIB$$d1075aca
說明是CGLib代理。
通過進一步測試,發現若是我實現接口UpdateRule
,可是注入方式使用類注入方式:
@Autowired private CustomerUpdateRule customerUpdateRule;
而且把proxyTargetClass
設置爲false,則運行就報以下錯誤:
嚴重: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@6a024a67] to prepare test instance [org.landy.business.rules.CustomerUpdateRuleTest@7fcf2fc1] org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.landy.business.rules.CustomerUpdateRuleTest': Unsatisfied dependency expressed through field 'customerUpdateRule'; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'customerUpdateRule' is expected to be of type 'org.landy.business.rules.stategy.CustomerUpdateRule' but was actually of type 'com.sun.proxy.$Proxy34' at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586)
以上說明了一個問題,使用接口實現的方式則會被默認爲JDK代理方式,若是須要使用CGLib代理,須要把proxyTargetClass
設置爲true
。
爲了再次驗證Spring AOP如何選擇JDK代理仍是CGLib代理,在此進行一個綜合測試。
測試前提:
UpdateRule
接口測試類使用接口方式注入
@Autowired private UpdateRule customerUpdateRule; //JDK代理方式必須以接口方式注入
測試:
配置proxyTargetClass
爲true
,運行結果以下:
customerCheckTest proxy class:class org.landy.business.rules.stategy.CustomerUpdateRule$$EnhancerBySpringCGLIB$$f5a34953 2018-10-05 15:28:42.820 [main] INFO org.landy.business.rules.aop.StatusCheckAspect - Status check around method start .... 2018-10-05 15:28:42.823 [main] INFO org.landy.business.rules.aop.StatusCheckAspect - Status check dynamic AOP,paramValues:2 AOP實際校驗邏輯。。。。2----currentStatus before statusCheck method start ... target class:org.landy.business.rules.stategy.CustomerUpdateRule@7164ca4c
說明爲CGLIb代理。
配置proxyTargetClass
爲false
,運行結果以下:
proxy class:class com.sun.proxy.$Proxy34 2018-10-05 15:20:59.894 [main] INFO org.landy.business.rules.aop.StatusCheckAspect - Status check around method start .... before statusCheck method start ... target class:org.landy.business.rules.stategy.CustomerUpdateRule@ae3540e
說明爲JDK代理。
以上測試說明,指定proxy-target-class爲true可強制使用cglib。
若是使用JDK動態代理,未使用接口方式注入(或者使用接口實現,並未配置proxyTargetClass
爲true),則會出現如下異常信息:
嚴重: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@6a024a67] to prepare test instance [org.landy.business.rules.CustomerUpdateRuleTest@7fcf2fc1] org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.landy.business.rules.CustomerUpdateRuleTest': Unsatisfied dependency expressed through field 'customerUpdateRule'; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'customerUpdateRule' is expected to be of type 'org.landy.business.rules.stategy.CustomerUpdateRule' but was actually of type 'com.sun.proxy.$Proxy34'
與生成的代理類型不一致,有興趣的同窗能夠Debug DefaultAopProxyFactory
類中的createAopProxy
方法便可知道兩種動態代理的區別。