SpringAOP之簡單實踐

Spring AOP建立在代理之上,所以先對代理有個簡單的認識也是很有必要的,下面結(jié)合代碼來進行簡要說明。

網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)建站!專注于網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、小程序開發(fā)、集團企業(yè)網(wǎng)站建設(shè)等服務(wù)項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了河津免費建站歡迎大家使用!

1,首先定義一個接口和實體對象

public class Student {
    public String name ;
    public int age ;
}
public interface IStudentService {
    /**
     * 添加學(xué)生
     * */
    void addStudent(Student student) ;
    /**
     * 刪除學(xué)生
     * */
    void removeStudent(String studentId) ; 
}
public class DefaultStudentService implements IStudentService {
    @Override
    public void addStudent(Student student) {
        System.out.println("新增學(xué)生信息");
    }
    @Override
    public void removeStudent(String studentId) {
        System.out.println("刪除ID為" + studentId+"的學(xué)生信息");
    }
}

2,Java的動態(tài)代理技術(shù)

Java的動態(tài)代理主要涉及到下面兩個類型
1)java.lang.reflect.InvocationHandler接口

/**
代理實例的調(diào)用處理程序?qū)崿F(xiàn)的接口;
每個代理實例都有一個關(guān)聯(lián)的調(diào)用處理程序。
在代理實例上調(diào)用方法時,方法調(diào)用將被處理并發(fā)送到其調(diào)用處理程序的invoke方法。
*/
public interface InvocationHandler {
    /**
            @param proxy 動態(tài)生成的代理對象實例
            @param method 被代理對象調(diào)用的方法
            @param args 被調(diào)用的方法的參數(shù)
            @return 從代理實例上的方法調(diào)用返回的值,其類型必須和被代理接口中所定義的返回類型兼容。
    */
    public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable;
}

2)java.lang.reflect.Proxy對象

簡單的說,Java動態(tài)代理就是通過Java的Proxy對象來創(chuàng)建某個實例對象的代理對象,在調(diào)用代理對象的時候便會觸發(fā)調(diào)用InvocationHandler的invoke方法,我們在invoke方法中可以添加一些額外的代碼來擴充能力,同時在invoke中我們可以判斷哪個方法被調(diào)用,然后通過反射執(zhí)行被代理對象上的這個方法。

3,使用Java動態(tài)代理實例

/**
     * Java的動態(tài)代理技術(shù)【代理整個接口類】
     */
    public static void javaDyncProxy() {
        // 要被代理的目標對象
        DefaultStudentService studentService = new DefaultStudentService();
        // 代理的調(diào)用處理器【當(dāng)我們通過動態(tài)代理對象調(diào)用任何一個方法時候,這個方法的調(diào)用就會被轉(zhuǎn)發(fā)到實現(xiàn)InvocationHandler接口類的invoke方法來調(diào)用】
        StudentServiceInvocationHandler invocationHandler = new StudentServiceInvocationHandler(studentService);
        // 創(chuàng)建代理對象
        IStudentService service = (IStudentService)Proxy.newProxyInstance(studentService.getClass().getClassLoader(),
                studentService.getClass().getInterfaces(), invocationHandler);
        service.addStudent(new Student());
    }
    public static class StudentServiceInvocationHandler implements InvocationHandler {
        private IStudentService target;
        public StudentServiceInvocationHandler(IStudentService studentService) {
            this.target = studentService;
        }

        /*
         * @param proxy
         * 真實對象的真實代理對象;InvocationHandler本身,例如這里的:StudentServiceInvocationHandler
         */
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("是的,你已經(jīng)是在使用Proxy了");
            return method.invoke(target, args);
        }
    }
    public static void main(String[] args) {
         javaDyncProxy() ;
    }

執(zhí)行main方法后,得到的打印輸入如下

是的,你已經(jīng)是在使用Proxy了
新增學(xué)生信息

4,Spring AOP

前面的文章中有介紹過Spring AOP中的一些概念,其中包括Advice和Pointcut。 Pointcut用于篩選類和方法,而Advice負責(zé)確實執(zhí)行點,通過兩則的結(jié)合就有了Advisor(切面)。

我們先看下SpringAOP中這些對象的關(guān)系。

Spring AOP之簡單實踐

由上圖可知
1)Pointcut接口依賴于ClassFilter和MethodMatcher兩個接口,通過這兩個接口來達到篩選類和方法的目的
2)Advice接口【是個Tag Interface】包含了眾多的子接口,通過子接口來擴展其功能,每個子接口都分別代表不同的方法執(zhí)行點(內(nèi)部的抽象方法便是添加增強代碼的地方)
3)Adisor接口依賴于Advice接口,代表一個類中的所有方法的某些執(zhí)行點,其最常用的子接口類型PointcutAdvisor有添加了對Pointcut接口的依賴,表示某些類中某些方法的某些執(zhí)行點

下面我們更進一步的看看各個接口都有哪些實現(xiàn)

Pointcut實現(xiàn)類關(guān)系圖

Spring AOP之簡單實踐

Advice接口關(guān)系圖

Spring AOP之簡單實踐

ThrowsAdvice是一個Tag interface,實現(xiàn)類具有以下任意一個或多個方法實現(xiàn)均可:
public void afterThrowing(Exception ex)
public void afterThrowing(RemoteException)
public void afterThrowing(Method method, Object[] args, Object target, Exception ex)
public void afterThrowing(Method method, Object[] args, Object target, ServletException ex)

Advisor關(guān)系圖

Spring AOP之簡單實踐

上面通過類圖展現(xiàn)了SpringAOP中幾個關(guān)鍵概念間的關(guān)系,下面再看看SpringProxy的類圖

Spring AOP之簡單實踐

1)ProxyCreatorSupport與AopProxyFactory關(guān)聯(lián),在內(nèi)部默認創(chuàng)建DefaultAopProxyFactory對象

2)AopProxyFactory依賴AopProxy接口,AopProxy的實現(xiàn)類包含了基于Java動態(tài)代理的JdkDynamicAopProxy和基于cglib的CglibAopProxy對象

3)我們在使用AopProxy的時候,內(nèi)部會根據(jù)我們的設(shè)置來動態(tài)的選擇使用Java動態(tài)代理還是基于cglib的代理。

下面通過示例代碼來說明Spring Aop的以上這些對象

使用ProxyFactory
/**
 * 定義“方位”以及對應(yīng)的增強代碼。
 * 使用時,如果沒提供具體的Ponitcut,該增強會織入到目標類的所有方法上。
 * */
public class StudentServiceAdvice implements MethodBeforeAdvice, AfterReturningAdvice,ThrowsAdvice {

    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("調(diào)用方法" + method.getName() +"前");

    }

    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("調(diào)用方法" + method.getName() +"返回后");
    }

    /**
     * 方法名必須是afterThrowing,前三個參數(shù)是可選【同時都出現(xiàn)或都不出現(xiàn)】,最后個參數(shù)不行是Throwable或子類。
     * 可以定義多個afterThrowing方法,Spring會自動選用最匹配的增強方法。
     * */
    public void afterThrowing(Method method, Object[] args, Object target,RuntimeException e) {
        System.out.println("調(diào)用方法" + method.getName() +"拋出異常后");
    }
}
/**
     * 只用增強應(yīng)用到類上的所有方法上
     */
    public static void springProxy() {
        // 要被代理的目標對象
        DefaultStudentService studentService = new DefaultStudentService();
        /*
         * 代理工廠根據(jù)代理配置在內(nèi)部使用AopProxy類型的代理創(chuàng)建代理對象,AopProxy的實現(xiàn)類有以下兩個: 
         * 1)JdkDynamicAopProxy :基于Java的動態(tài)代理技術(shù) 
         * 2)Cglib2AopProxy : 基于CGLib的動態(tài)代理技術(shù)
         * 在使用ProxyFactory的時候,如果通過setInterface()方法指定目標接口進行代理,則使用JdkDynamicAopProxy;
         * 如果針對類的代理或者設(shè)置SetOptimize(true),則使用Cglib2AopProxy;
         */
        ProxyFactory factory = new ProxyFactory();
        // 設(shè)置要被代理的接口類型
        factory.setInterfaces(studentService.getClass().getInterfaces());
        // 設(shè)置代理的目標對象
        factory.setTarget(studentService);
        // 為代理目標添加增強[Advice包含了橫切代碼和連接點信息,所以本身就是一個簡單的切面]
        factory.addAdvice(new StudentServiceAdvice());
        // 生成代理實例
        IStudentService proxy = (IStudentService) factory.getProxy();
        // 調(diào)用方法
        proxy.addStudent(new Student("test", 22));
        proxy.removeStudent("10001");
    }
執(zhí)行后的輸出結(jié)果:
調(diào)用方法addStudent前
新增學(xué)生信息
調(diào)用方法addStudent返回后
調(diào)用方法removeStudent前
刪除ID為10001的學(xué)生信息
調(diào)用方法removeStudent返回后
使用AspectJProxyFactory
        <!-- AspectJ -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.9.4</version>
        </dependency>
@Aspect
public class CommAspect {

    /**
     * 前置增強
     * 所有目標類中的所有addStudent方法
     * */
    @Before("execution (* addStudent(..))")
    public void defore(JoinPoint joinPoint) {
        System.out.println(">>>>befor addStudent");
    }
}

public static void springAspectProxy() {
        // 要被代理的目標對象
        DefaultStudentService studentService = new DefaultStudentService();
        // 基于AspectJ的代理工廠
        AspectJProxyFactory factory = new AspectJProxyFactory();
        // 設(shè)置代理目標
        factory.setTarget(studentService);
        // 添加切面類
        factory.addAspect(CommAspect.class);
        // 生成代理實例
        IStudentService proxy = (IStudentService) factory.getProxy();
        // 調(diào)用方法
        proxy.addStudent(new Student("test", 22));
        proxy.removeStudent("10001");
    }

執(zhí)行后輸出:

>>>>befor addStudent
新增學(xué)生信息
刪除ID為10001的學(xué)生信息

網(wǎng)站題目:SpringAOP之簡單實踐
網(wǎng)站路徑:http://muchs.cn/article12/gdspdc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站網(wǎng)站排名、品牌網(wǎng)站建設(shè)、自適應(yīng)網(wǎng)站網(wǎng)站策劃、Google

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作