Java設計模式綜合運用(動態(tài)代理+Spring AOP)

AOP設計模式通常運用在日志,校驗等業(yè)務場景,本文將簡單介紹基于Spring的AOP代理模式的運用。

1. 代理模式

1.1 概念

代理(Proxy)是一種提供了對目標對象另外的訪問方式,即通過代理對象訪問目標對象。這樣做的好處是:可以在目標對象實現(xiàn)的基礎上,增強額外的功能操作,即擴展目標對象的功能。
這里使用到編程中的一個思想:不要隨意去修改別人已經(jīng)寫好的代碼或者方法,如果需改修改,可以通過代理的方式來擴展該方法。

1.2 靜態(tài)代理

靜態(tài)代理在使用時,需要定義接口或者父類,被代理對象與代理對象一起實現(xiàn)相同的接口或者是繼承相同父類。

1.3 動態(tài)代理

1.3.1 JDK代理

JDK動態(tài)代理有以下特點:
1.代理對象,不需要實現(xiàn)接口
2.代理對象的生成,是利用JDK的API,動態(tài)的在內(nèi)存中構建代理對象(需要我們指定創(chuàng)建代理對象/目標對象實現(xiàn)的接口的類型)
3.動態(tài)代理也叫做:JDK代理,接口代理

1.3.2 CGLib代理

Cglib代理,也叫作子類代理,它是在內(nèi)存中構建一個子類對象從而實現(xiàn)對目標對象功能的擴展。

  1. JDK的動態(tài)代理有一個限制,就是使用動態(tài)代理的對象必須實現(xiàn)一個或多個接口,如果想代理沒有實現(xiàn)接口的類,就可以使用Cglib實現(xiàn)。
  2. Cglib是一個強大的高性能的代碼生成包,它可以在運行期擴展java類與實現(xiàn)java接口。它廣泛的被許多AOP的框架使用,例如Spring AOP和synaop,為他們提供方法的interception(攔截)。
  3. Cglib包的底層是通過使用一個小而塊的字節(jié)碼處理框架ASM來轉換字節(jié)碼并生成新的類。不鼓勵直接使用ASM,因為它要求你必須對JVM內(nèi)部結構包括class文件的格式和指令集都很熟悉。

2. Spring AOP

2.1 Spring AOP原理

AOP實現(xiàn)的關鍵在于AOP框架自動創(chuàng)建的AOP代理,AOP代理主要分為靜態(tài)代理和動態(tài)代理,靜態(tài)代理的代表為AspectJ;而動態(tài)代理則以Spring AOP為代表。本文以Spring AOP的實現(xiàn)進行分析和介紹。

Spring AOP使用的動態(tài)代理,所謂的動態(tài)代理就是說AOP框架不會去修改字節(jié)碼,而是在內(nèi)存中臨時為方法生成一個AOP對象,這個AOP對象包含了目標對象的全部方法,并且在特定的切點做了增強處理,并回調(diào)原對象的方法。

Spring AOP中的動態(tài)代理主要有兩種方式,JDK動態(tài)代理CGLIB動態(tài)代理。JDK動態(tài)代理通過反射來接收被代理的類,并且要求被代理的類必須實現(xiàn)一個接口。JDK動態(tài)代理的核心是InvocationHandler接口和Proxy類。

如果目標類沒有實現(xiàn)接口,那么Spring AOP會選擇使用CGLIB來動態(tài)代理目標類。CGLIB(Code Generation Library),是一個代碼生成的類庫,可以在運行時動態(tài)的生成某個類的子類,注意,CGLIB是通過繼承的方式做的動態(tài)代理,因此如果某個類被標記為final,那么它是無法使用CGLIB做動態(tài)代理的。

注意:以上片段引用自文章Spring AOP的實現(xiàn)原理,如有冒犯,請聯(lián)系筆者刪除之,謝謝!

Spring AOP判斷是JDK代理還是CGLib代理的源碼如下(來自org.springframework.aop.framework.DefaultAopProxyFactory):

@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);
    }
}

由代碼發(fā)現(xiàn),如果配置proxyTargetClass = true了并且目標類非接口的情況,則會使用CGLib代理,否則使用JDK代理。

2.2 Spring AOP配置

Spring AOP的配置有兩種方式,XML和注解方式。

2.2.1 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>

2.2.2 注解配置

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();
    }

}

2.2.3 依賴包

需要使用Spring AOP需要引入以下Jar包:

<properties>
    <spring.version>5.0.8.RELEASE</spring.version>
    <aspectj.version>1.8.7</aspectj.version>
</properties>
<!-- aspectjrt.jar包主要是提供運行時的一些注解,靜態(tài)方法等等東西,通常我們要使用aspectJ的時候都要使用這個包。 -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>${aspectj.version}</version>
</dependency>
<!-- aspectjweaverjar包主要是提供了一個java agent用于在類加載期間織入切面(Load time weaving)。
    并且提供了對切面語法的相關處理等基礎方法,供ajc使用或者供第三方開發(fā)使用。這個包一般我們不需要顯式引用,除非需要使用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>

2.2.4 配置單元測試

以上兩種配置方式,單元測試需要注意一個地方就是引入配置的方式不一樣,區(qū)別如下:

  1. XML方式

    @ContextConfiguration(locations = { "classpath:spring.xml" }) //加載配置文件
    @RunWith(SpringJUnit4ClassRunner.class)  //使用junit4進行測試
    public class SpringTestBase extends AbstractJUnit4SpringContextTests {
    }
    
  2. 注解方式

@ContextConfiguration(classes = ApplicationConfigure.class)
@RunWith(SpringJUnit4ClassRunner.class)  //使用junit4進行測試
public class SpringTestBase extends AbstractJUnit4SpringContextTests {
}

配置好了以后,以后所有的測試類都繼承SpringTestBase類即可。

3. 項目演示

3.1 邏輯梳理

本文將以校驗某個業(yè)務邏輯為例說明Spring AOP代理模式的運用。

按照慣例,還是以客戶信息更新校驗為例,假設有個校驗類如下:

/**
 * @author landyl
 * @create 2:22 PM 09/30/2018
 */
@Component
public class CustomerUpdateRule implements UpdateRule {

    //利用自定義注解,進行AOP切面編程,進行其他業(yè)務邏輯的校驗操作
    @StatusCheck
    public CheckResult check(String updateStatus, String currentStatus) {
        System.out.println("CustomerUpdateRule:在此還有其他業(yè)務校驗邏輯。。。。"+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());
        //獲得自定義注解的參數(shù)
        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

3.2 邏輯測試

3.2.1 JDK動態(tài)代理

JDK動態(tài)代理必須實現(xiàn)一個接口,本文實現(xiàn)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:在此還有其他業(yè)務校驗邏輯。。。。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代理。

3.2.2 CGLib動態(tài)代理

使用CGlib可以不用接口(經(jīng)測試,用了接口好像也沒問題)。在測試類中,必須使用實現(xiàn)類方式注入:

 @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 {

}

不過發(fā)現(xiàn)我并未配置proxyTargetClass = true也可以正常運行,有點奇怪。(按理說,默認是為false)

運行結果生成的代理類為:

proxy class:class org.landy.business.rules.stategy.CustomerUpdateRule$$EnhancerBySpringCGLIB$$d1075aca

說明是CGLib代理。

經(jīng)過進一步測試,發(fā)現(xiàn)如果我實現(xiàn)接口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)

以上說明了一個問題,使用接口實現(xiàn)的方式則會被默認為JDK代理方式,如果需要使用CGLib代理,需要把proxyTargetClass設置為true

3.2.3 綜合測試

為了再次驗證Spring AOP如何選擇JDK代理還是CGLib代理,在此進行一個綜合測試。

測試前提:

  1. 實現(xiàn)UpdateRule接口

  2. 測試類使用接口方式注入

    @Autowired
    private UpdateRule customerUpdateRule; //JDK代理方式必須以接口方式注入
    

測試:

配置proxyTargetClasstrue,運行結果如下:

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代理。

配置proxyTargetClassfalse,運行結果如下:

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。

3.3 常見問題

如果使用JDK動態(tài)代理,未使用接口方式注入(或者使用接口實現(xiàn),并未配置proxyTargetClass為true),則會出現(xiàn)以下異常信息:

嚴重: 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方法即可知道兩種動態(tài)代理的區(qū)別。

事例代碼地址:https://github.com/landy8530/DesignPatterns

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,941評論 18 139
  • 本文是我自己在秋招復習時的讀書筆記,整理的知識點,也是為了防止忘記,尊重勞動成果,轉載注明出處哦!如果你也喜歡,那...
    波波波先森閱讀 12,322評論 6 86
  • 我有一年多沒有一個人坐車外出了,在別人覺得小事一樁,在我卻是實屬難得。所以,當我此次一個人輕裝上路,竟然莫名地感動...
    風的細語閱讀 242評論 0 1
  • 忽爾驚覺,不知什么時候已失去了在紙上書寫的欲望與表達的最最基本的形式。 而微信、QQ甚至于我所沒用...
    梅雨中閱讀 255評論 0 0
  • 第一次注冊,我將會以一個嘻哈音樂愛好者的身份,講述我的故事。
    EyW閱讀 270評論 0 0