SSH框架之Spring第三篇

1.1 AOP概述
        1.1.1 什麼是AOP?
            AOP : 全稱是Aspect Oriented Progamming既 : 面向切面編程.經過預編譯方式和運行期動態代理實現程序功能的統一維護的一種技術.
            簡單的說它就是把咱們程序重複的代碼抽取出來,在須要執行的時候,使用動態代理的技術,在不修改源碼的基礎上,對咱們的已有方法進行加強.
        1.1.2 AOP的做用及優點
            做用 : 
                在程序運行期間,不修改源碼對已有方法進行加強.
            優點 :
                減小重複代碼,提升開發效率,維護方便.
        1.1.3 AOP的實現方式 : 使用動態代理技術
        1.2.2.1 動態代理的特色 :
            字節碼隨用隨建立,隨用隨加載.
            它與靜態代理的區別也在於此.由於靜態代理是字節碼一上來就建立好,並完成加載.
            裝飾着模式就是靜態代理的一種體現.
        1.2.2.2 動態代理經常使用的有兩種方式    
            基於接口的動態代理
                提供者 : JDK官方的Proxy類.
                要求   : 被代理來最少實現一個接口.
            基於子類的動態代理
                提供者 : 第三方的CGLib,若是報asmxxxx異常,須要導入asm.jar.
                要求   : 被代理類不能用final修飾的類(最終類).
    1.3 Spring中的AOP
        1.3.1 關於代理的選擇
            在Spring中,框架根據目標類實現了接口決定採用哪一種動態代理的方式.
        1.3.2 AOP相關術語
            Joinpoint(鏈接點) : 所謂鏈接點是指那些被攔截到的點.在Spring中,這些點值得是方法,由於spring只支持方法類型的鏈接點.
            Pointcut(切入點) : 所謂切入點是指咱們要對那些Joinpoint進行攔截的定義.
            Advice(通知/加強) : 所謂通知是指攔截到Joinpoint以後所要作的事情就是通知.
                通知的類型 : 前置通知,後置通知,異常通知,最終通知,環繞通知.
            Introduction(引介) : 是一種特殊的通知在不修改類代碼的前提下,Introduction能夠在運行期爲類動態地添加一些方法或Field.
            Target(目的對象) : 
                代理的目標對象.
            Weaving(織入) : 
                是值把加強應用到目標對象來建立新的代理對象的過程.
                spring採用動態代理織入,而AspectJ採用編譯器織入和類轉載期織入.
            Proxy (代理) : 
                一個類被AOP織入加強後,就是產生一個結果代理類.
            Aspect(切面) : 
                是切入點和通知(引介) 的結合.
    1.4 基於XML的AOP配置
        1.4.1 導入包
        1.4.2 準備接口
        1.4.3 建立配置文件導入約束
            <?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.xsd
                               http://www.springframework.org/schema/aop 
                               http://www.springframework.org/schema/aop/spring-aop.xsd">

            </beans>
        
        2.1.4第四步:把客戶的業務層配置到spring容器中
            <!-- 把資源交給spring來管理 -->
            <bean id="customerService" class="com.baidu.service.impl.CustomerServiceImpl"/>
        2.1.5第五步:製做通知(加強的類)
            /**
             * 一個記錄日誌的工具類
            */
            public class Logger {
                /**
                 * 指望:此方法在業務核心方法執行以前,就記錄日誌
                 */
                public void beforePrintLog(){
                    System.out.println("Logger類中的printLog方法開始記錄日誌了。。。。");
                }
            }
        2.2配置步驟
            2.2.1第一步:把通知類用bean標籤配置起來
            <!-- 把有公共代碼的類也讓spring來管理(把通知類也交給spring來管理) -->
            <bean id="logger" class="com.baidu.util.Logger"></bean>
            2.2.2第二步:使用aop:config聲明aop配置
            <!-- aop的配置 -->
            <aop:config>
                <!-- 配置的代碼都寫在此處 -->    
            </aop:config>
            2.2.3第三步:使用aop:aspect配置切面
            <!-- 配置切面 :此標籤要出如今aop:config內部
                id:給切面提供一個惟一標識
                ref:引用的是通知類的bean的id
            -->
            <aop:aspect id="logAdvice" ref="logger">
                    <!--配置通知的類型要寫在此處-->
            </aop:aspect>
            2.2.4第四步:使用aop:before配置前置通知
            <!-- 用於配置前置通知:指定加強的方法在切入點方法以前執行 
                    method:用於指定通知類中的加強方法名稱
                    ponitcut-ref:用於指定切入點的表達式的引用    
            -->
            <aop:before method="beforePrintLog" pointcut-ref="pt1"/>
            2.2.5第五步:使用aop:pointcut配置切入點表達式
            <aop:pointcut expression="execution(public void com.baidu.service.impl.CustomerServiceImpl.saveCustomer())" 
            id="pt1"/>
            2.3切入點表達式說明
            execution:
                    匹配方法的執行(經常使用)        
                    execution(表達式)
            表達式語法:execution([修飾符] 返回值類型 包名.類名.方法名(參數))
            寫法說明:
                全匹配方式:
                    public void com.baidu.service.impl.CustomerServiceImpl.saveCustomer()
                訪問修飾符能夠省略    
                    void com.baidu.service.impl.CustomerServiceImpl.saveCustomer()
                返回值可使用*號,表示任意返回值
                    * com.baidu.service.impl.CustomerServiceImpl.saveCustomer()
                包名可使用*號,表示任意包,可是有幾級包,須要寫幾個*
                    * *.*.*.*.CustomerServiceImpl.saveCustomer()
                使用..來表示當前包,及其子包
                    * com..CustomerServiceImpl.saveCustomer()
                類名可使用*號,表示任意類
                    * com..*.saveCustomer()
                方法名可使用*號,表示任意方法
                    * com..*.*()
                參數列表可使用*,表示參數能夠是任意數據類型,可是必須有參數
                    * com..*.*(*)
                參數列表可使用..表示有無參數都可,有參數能夠是任意類型
                    * com..*.*(..)
                全通配方式:
                    * *..*.*(..)

            2.4經常使用標籤
            2.4.1<aop:config>
            做用:
                用於聲明開始aop的配置
            2.4.2<aop:aspect>
            做用:
                用於配置切面。
            屬性:
                id:給切面提供一個惟一標識。
                ref:引用配置好的通知類bean的id。
            2.4.3<aop:pointcut>
            做用:
                用於配置切入點表達式
            屬性:
                expression:用於定義切入點表達式。
                id:用於給切入點表達式提供一個惟一標識。
            2.4.4<aop:before>
            做用:
                用於配置前置通知
            屬性:
                method:指定通知中方法的名稱。
                pointct:定義切入點表達式
                pointcut-ref:指定切入點表達式的引用
            2.4.5<aop:after-returning>
            做用:
                用於配置後置通知
            屬性:
                method:指定通知中方法的名稱。
                pointct:定義切入點表達式
                pointcut-ref:指定切入點表達式的引用
            2.4.6<aop:after-throwing>
            做用:
                用於配置異常通知
            屬性:
                method:指定通知中方法的名稱。
                pointct:定義切入點表達式
                pointcut-ref:指定切入點表達式的引用
            2.4.7<aop:after>
            做用:
                用於配置最終通知
            屬性:
                method:指定通知中方法的名稱。
                pointct:定義切入點表達式
                pointcut-ref:指定切入點表達式的引用
            2.4.8<aop:around>
            做用:
                用於配置環繞通知
            屬性:
                method:指定通知中方法的名稱。
                pointct:定義切入點表達式
                pointcut-ref:指定切入點表達式的引用
            2.5通知的類型
            2.5.1類型說明
            <!-- 配置通知的類型
                aop:before:
                    用於配置前置通知。前置通知的執行時間點:切入點方法執行以前執行
                aop:after-returning:
                    用於配置後置通知。後置通知的執行時間點:切入點方法正常執行以後。它和異常通知只能有一個執行
                aop:after-throwing
                    用於配置異常通知。異常通知的執行時間點:切入點方法執行產生異常後執行。它和後置通知只能執行一個。
                aop:after
                    用於配置最終通知。最終通知的執行時間點:不管切入點方法執行時是否有異常,它都會在其後面執行。
                aop:around
                    用於配置環繞通知。他和前面四個不同,他不是用於指定通知方法什麼時候執行的。
            -->            
            <aop:before method="beforePrintLog" pointcut-ref="pt1"/>
            <aop:after-returning method="afterReturningPrintLog"  pointcut-ref="pt1"/>
            <aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"/>
            <aop:after method="afterPrintLog" pointcut-ref="pt1"/>
            <aop:around method="aroundPringLog" pointcut-ref="pt1"/>
            2.5.2環繞通知的特殊說明
            /**
                 * 環繞通知
                 *     它是spring框架爲咱們提供的一種能夠在代碼中手動控制加強部分何時執行的方式。
                 * 問題:
                 *     當咱們配置了環繞通知以後,加強的代碼執行了,業務核心方法沒有執行。
                 * 分析:
                 *     經過動態代理咱們知道在invoke方法中,有明確調用業務核心方法:method.invoke()。
                 *     咱們配置的環繞通知中,沒有明確調用業務核心方法。
                 * 解決:
                 *     spring框架爲咱們提供了一個接口:ProceedingJoinPoint,它能夠做爲環繞通知的方法參數
                 *     在環繞通知執行時,spring框架會爲咱們提供該接口的實現類對象,咱們直接使用就行。
                 *     該接口中有一個方法proceed(),此方法就至關於method.invoke()
                 */
                public void aroundPringLog(ProceedingJoinPoint pjp){
                    try {
                        System.out.println("前置通知:Logger類的aroundPringLog方法記錄日誌");
                        pjp.proceed();
                        System.out.println("後置通知:Logger類的aroundPringLog方法記錄日誌");
                    } catch (Throwable e) {
                        System.out.println("異常通知:Logger類的aroundPringLog方法記錄日誌");
                        e.printStackTrace();
                    }finally{
                        System.out.println("最終通知:Logger類的aroundPringLog方法記錄日誌");
                    }
                }
        3.1 基於註解的AOP配置
            3.1.1 環境搭建 準備業務層和接口並用註解配置
            3.1.2 導入jar包
            3.1.3 建立spring的配置文件並導入約束
            3.1.4 第四步:把資源使用註解讓spring來管理
            3.1.5 第五步 : 在配置文件中指定spring要掃描的包
                <-- 告知spring,在建立容器時要掃描的包-->
                <context:component-scan base-package="com.baidu"></context:component-scan>
                
        3.2 配置步驟
            3.2.1第一步:把通知類也使用註解配置
            /**
             * 一個記錄日誌的工具類
             */
            @Component("logger")
            public class Logger {
                /**
                 * 指望:此方法在業務核心方法執行以前,就記錄日誌
                 * 前置通知
                 */
                public void beforePrintLog(){
                    System.out.println("前置通知:Logger類中的printLog方法開始記錄日誌了");
                }
            }
            3.2.2第二步:在通知類上使用@Aspect註解聲明爲切面
            /**
             * 一個記錄日誌的工具類
             */
            @Component("logger")
            @Aspect//代表當前類是一個切面類
            public class Logger {
                /**
                 * 指望:此方法在業務核心方法執行以前,就記錄日誌
                 * 前置通知
                 */
                public void beforePrintLog(){
                    System.out.println("前置通知:Logger類中的printLog方法開始記錄日誌了");
                }
            }
            3.2.3第三步:在加強的方法上使用@Before註解配置前置通知
                /**
                 * 指望:此方法在業務核心方法執行以前,就記錄日誌
                 * 前置通知
                 */
                @Before("execution(* com.baidu.service.impl.*.*(..))")//表示前置通知
                public void beforePrintLog(){
                    System.out.println("前置通知:Logger類中的printLog方法開始記錄日誌了");
                }
            3.2.4第四步:在spring配置文件中開啓spring對註解AOP的支持
            <!-- 開啓spring對註解AOP的支持 -->
            <aop:aspectj-autoproxy/>
            3.3經常使用註解
            3.3.1@Aspect:
            做用:
                把當前類聲明爲切面類。
            3.3.2@Before:
            做用:
                把當前方法當作是前置通知。
            屬性:
                value:用於指定切入點表達式,還能夠指定切入點表達式的引用。
            3.3.3@AfterReturning
            做用:
                把當前方法當作是後置通知。
            屬性:
                value:用於指定切入點表達式,還能夠指定切入點表達式的引用。
            3.3.4@AfterThrowing
            做用:
                把當前方法當作是異常通知。
            屬性:
                value:用於指定切入點表達式,還能夠指定切入點表達式的引用。
            3.3.5@After
            做用:
                把當前方法當作是最終通知。
            屬性:
                value:用於指定切入點表達式,還能夠指定切入點表達式的引用。
            3.3.6@Around
            做用:
                把當前方法當作是環繞通知。
            屬性:
                value:用於指定切入點表達式,還能夠指定切入點表達式的引用。
            3.3.7@Pointcut
            做用:
                指定切入點表達式
            屬性:
                value:指定表達式的內容
            3.4不使用XML的配置方式
            @Configuration
            @ComponentScan(basePackages="com.baidu")
            @EnableAspectJAutoProxy
            public class SpringConfiguration {
            }
    總結 :
        方法稱爲鏈接點.
        切入點 : 具體對那個方法作加強.切入點的表達式.
        Advice(通知/加強) : 對save方法作加強,編寫程序加強要作的事情.
        通知類型 : 前置通知,後置通知,最終通知,異常通知和環繞通知.
        Target(目標對象) : UserServiceImpl對象
        Proxy (代理) : 生成的代理對象
        Aspect(切面) : 抽象的概念
            切面 = 切入點 + 通知.
        Weaving(織入) : 是指把加強應用到目標對象來建立新的代理對象的過程.
    AOP配置文件開發步驟 :
        1 : 導入jar包
        2 : 編寫切面類,編寫通知的方法(本身來編寫的)
        3 : 配置切面類,進行IOC的管理
        4 : 編寫AOP的加強.
    <aop:config>
        <!--配置切面 = 切入點(表達式) + 通知 -->
        <aop:aspect ref="myXmlAspect">
            <!--選擇通知的類型,前置通知-->
            <aop:before method="log" pointcut="execution(public void com.baidu.demo1.UserServiceImpl.save())"/>
        </aop:aspect>
    </aop:config>
    <!-- 開啓註解掃描 -->
    <context:component-scan base-package="com.baidu.demo1"/>
    
    <!-- 開啓註解AOP -->
    <aop:aspectj-autoproxy/>
        package com.baidu.demo1;

        import org.aspectj.lang.ProceedingJoinPoint;
        import org.aspectj.lang.annotation.After;
        import org.aspectj.lang.annotation.AfterReturning;
        import org.aspectj.lang.annotation.AfterThrowing;
        import org.aspectj.lang.annotation.Around;
        import org.aspectj.lang.annotation.Aspect;
        import org.aspectj.lang.annotation.Before;
        import org.aspectj.lang.annotation.Pointcut;
        import org.springframework.stereotype.Component;

        /**
         * 註解方式的切面類
         * 聲明當前類是切面類
         * @author Administrator
         */
        @Component("myAnnoAspect")
        @Aspect        // 聲明當前類是切面類 = 切入點表達式 + 通知類型
        public class MyAnnoAspect {
            
            /**
             * 通知方法
             * 配置通知類型,註解的屬性編寫的是切入點的表達式
             * 通知類型所有采用註解方式
             *         @Before                    前置通知
             *         @AfterReturning            後置通知,目標對象方法執行成功
             *         @AfterThrowing            異常通知
             *         @After                    最終通知
             */
            // @Before(value="execution(public * com.baidu.demo1.*.save(..))")
            // @AfterReturning(value="execution(public * com.baidu.demo1.*.save(..))")
            // @AfterThrowing(value="execution(public * com.baidu.demo1.*.save(..))")
            // @After(value="execution(public * com.baidu.demo1.*.save(..))")
            public void log(){
                System.out.println("記錄日誌...");
            }
            
            /**
             * 環繞通知
             */
            // @Around(value="execution(public * com.baidu.demo1.*.save(..))")
            @Around(value="MyAnnoAspect.fn()")
            public void arond(ProceedingJoinPoint pp){
                try {
                    System.out.println("記錄日誌...");
                    // 讓目標對象方法執行
                    pp.proceed();
                    System.out.println("記錄日誌...");
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
            
            /**
             * 定義切入點的表達式
             */
            @Pointcut(value="execution(public * com.baidu.demo1.*.save(..))")
            public void fn(){}
            
        }
    
    基於子類的動態代理:
        package com.baidu.demo2;

        import java.lang.reflect.Method;

        import org.springframework.cglib.proxy.Enhancer;
        import org.springframework.cglib.proxy.MethodInterceptor;
        import org.springframework.cglib.proxy.MethodProxy;

        /**
         * 使用cglib方式生成代理對象
         * 不用實現接口
         * @author Administrator
         */
        public class MyCglibProxy {
            
            /**
             * 獲取到代理對象
             * @return
             */
            public static RoleServiceImpl getProxy(final RoleServiceImpl role){
                Enhancer e = new Enhancer();
                // 設置父類
                e.setSuperclass(role.getClass());
                // 設置回調函數
                e.setCallback(new MethodInterceptor() {
                    
                    // 調用代理對象的方法,那麼intercept方法就會執行
                    public Object intercept(Object arg0, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                        // 讓目標對象方法執行
                        Object invoke = methodProxy.invoke(role, args);
                        // 加強
                        System.out.println("記錄日誌...");
                        return invoke;
                    }
                });
                // 建立代理對象
                Object proxy = e.create();
                // 把代理對象返回
                return (RoleServiceImpl) proxy;
            }

        }
    <?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:context="http://www.springframework.org/schema/context"
            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.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx.xsd">
            
            <!-- 管理service -->
            <bean id="userService" class="com.baidu.demo1.UserServiceImpl"/>
            
            <!-- 先配置切面類 -->
            <bean id="myXmlAspect" class="com.baidu.demo1.MyXmlAspect"/>
            
            <!-- 配置AOP的加強 
            <aop:config>
            -->
                <!-- 配置切面 = 切入點 (表達式)+ 通知 
                <aop:aspect ref="myXmlAspect">
                -->
                    <!-- 選擇通知的類型,前置通知 
                    <aop:before method="log" pointcut="execution(public void com.baidu.demo1.UserServiceImpl.save())"/>
                </aop:aspect>
            </aop:config>
            -->
            
            <!-- 配置AOP的加強 -->
            <aop:config>
                <!-- 編寫切入點的表達式 -->
                <aop:pointcut expression="execution(public void com.baidu.demo1.UserServiceImpl.save())" id="pt"/>
                <aop:aspect ref="myXmlAspect">
                    <aop:before method="log" pointcut-ref="pt"/>
                </aop:aspect>
            </aop:config>
            
                <!--  
                切入點的表達式:
                    execution()            固定寫法
                    public                能夠省略不寫
                    void                方法的返回值,能夠寫 * 號
                    包結構                也能夠 * 號,不能省略不寫
                    UserServiceImpl        類,能夠編寫 * 號,常見的編寫的寫法:*ServiceImpl
                    方法                    能夠編寫*號  save*  saveUser  saveDept
                    參數列表                編寫..    指的可變參數
                
                需求:對項目中的service的save方法進行加強
                    execution(public * com.baidu.*.*ServiceImpl.3save*(..))
            -->
            <aop:config>
                <!-- <aop:pointcut expression="execution(public void com.baidu.demo1.UserServiceImpl.update())" id="pt"/> -->
                <!-- <aop:pointcut expression="execution(void com.baidu.demo1.UserServiceImpl.save())" id="pt"/> -->
                <!-- <aop:pointcut expression="execution(* com.baidu.demo1.UserServiceImpl.save())" id="pt"/> -->
                <!-- <aop:pointcut expression="execution(* com.baidu.*.UserServiceImpl.save())" id="pt"/> -->
                <!-- <aop:pointcut expression="execution(* com.baidu.*.*ServiceImpl.save())" id="pt"/> -->
                <!-- <aop:pointcut expression="execution(* com.baidu.*.*ServiceImpl.save*())" id="pt"/> -->
                <aop:pointcut expression="execution(* com.baidu.*.*ServiceImpl.save*(..))" id="pt"/>
                <aop:aspect ref="myXmlAspect">
                    <aop:before method="log" pointcut-ref="pt"/>
                </aop:aspect>
            </aop:config>
            
            <!-- 配置AOP的加強 -->
            <aop:config>
                <!-- 編寫切入點的表達式 -->
                <aop:pointcut expression="execution(public void com.baidu.demo1.UserServiceImpl.save())" id="pt"/>
                <aop:aspect ref="myXmlAspect">
                    <!-- 前置通知 
                    <aop:before method="log" pointcut-ref="pt"/>
                    -->
                    <!-- 後置通知:目標對象方法執行成功後,通知方法才執行 
                    <aop:after-returning method="log" pointcut-ref="pt"/>
                    -->
                    <!-- 異常通知:目標對象方法出現異常後,通知執行 
                    <aop:after-throwing method="log" pointcut-ref="pt"/>
                    -->
                    <!-- 最終通知:目標對象方法執行成功或失敗,都會執行 
                    <aop:after method="log" pointcut-ref="pt"/>
                    -->
                    <!-- 環繞通知:在目標對象方法執行先後去加強,問題,默認捕獲目標對象的方法,手動讓目標對象的方法執行 -->
                    <aop:around method="around" pointcut-ref="pt"/>
                </aop:aspect>
            </aop:config>
            
        </beans>

    import javax.annotation.Resource;

    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

    @RunWith(value=SpringJUnit4ClassRunner.class)
    // @ContextConfiguration(value="classpath:applicationContext.xml")    //入門案例
    // @ContextConfiguration(value="classpath:applicationContext2.xml")    // 切入點的表達式
    @ContextConfiguration(value="classpath:applicationContext3.xml")   // 通知類型
    public class Demo1 {
        
        @Resource(name="userService")
        private UserService userService;
        
        /**
         * AOP的入門程序
         */
        @Test
        public void run1(){
            userService.save();
        }

    }
相關文章
相關標籤/搜索