1. 程式人生 > >應用Spring的註解方式實現AOP

應用Spring的註解方式實現AOP

一、使用例項

1、匯入需要的包

首先,為了使用Spring的AOP註解功能,必須在pom.xml中匯入如下幾個包。

<properties>
        <org.springframework-version>3.2.9.RELEASE</org.springframework-version>
        <commons-logging.version>1.1</commons-logging.version>
        <org.slf4j-version>1.7.2</org.slf4j-version>
    </properties>


    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${org.springframework-version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.dbunit</groupId>
            <artifactId>dbunit</artifactId>
            <version>2.4.6</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>${commons-logging.version}</version>
        </dependency>


        <!-- Logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${org.slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.15</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.mail</groupId>
                    <artifactId>mail</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
            </exclusions>
            <scope>runtime</scope>
        </dependency>


        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.6.11</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.11</version>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.1</version>
        </dependency>
    </dependencies>

2、配置檔案applicationContext.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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       <span style="color:#FF0000;">http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-2.5.xsd</span>
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">


    <!-- 宣告註解方式載入bean-->
    <context:annotation-config/>

    <!-- 要載入的bean的包路徑-->
    <context:component-scan base-package="com.meituan.hyt.test.service"/>

    <!-- 自動掃描被@Aspect註解的bean-->
    <aop:aspectj-autoproxy/>

    <bean id="myInterceptor" class="com.meituan.hyt.test.aop.MyInterceptor"/>
</beans>

3、編寫自己的業務介面和實現類,註解為spring bean

package com.meituan.hyt.test.service;

public interface PersonService {
    public void save(String name);

    public void update(int name);

    public void throwException();

    public String getPersonName();

}


package com.meituan.hyt.test.service;

import org.springframework.stereotype.Service;

@Service(value = "personService")
public class PersonServiceImpl implements PersonService {

    @Override
    public String getPersonName() {
        System.out.println("我是getPersonName()方法。。。");
        return "返回結果";
    }


    @Override
    public void save(String name) {
        System.out.println("我是save()方法。。。");
    }

    @Override
    public void update(int name) {
        System.out.println("我是update()方法。。。");
    }

    @Override
    public void throwException() {
        System.out.println("我是throwException()方法。。。");
        throw new RuntimeException("異常了。。");
    }
}


4、編寫切面

package com.meituan.hyt.test.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;

/**
 * Created by heyutao on 15/11/2.
 */
@Aspect
public class MyInterceptor {
    @Pointcut("execution(* com.meituan.hyt.test.service.*.*(..))")

    //宣告一個切入點
    private void anyMethod() {
    }

    @Before("anyMethod() && args(name)")//宣告前置通知
    public void doBefore(String name) {
        System.out.println("前置通知");
        System.out.println("---" + name + "---");
    }

    @AfterReturning(pointcut = "anyMethod()", returning = "result")//聲明後置通知
    public void doAfterReturning(String result) {
        System.out.println("後置通知");
        System.out.println("---" + result + "---");
    }

    @AfterThrowing(pointcut = "anyMethod()", throwing = "e")//宣告例外通知
    public void doAfterThrowing(Exception e) {
        System.out.println("例外通知");
        System.out.println(e.getMessage());
    }

    @After("anyMethod()")//宣告最終通知
    public void doAfter() {
        System.out.println("最終通知");
    }

    @Around("anyMethod()")//宣告環繞通知
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("進入方法---環繞通知");
        //顯示呼叫,確保被代理的方法被呼叫
        Object o = pjp.proceed();
        System.out.println("退出方法---環繞通知");
        return o;
    }
}

1、@Pointcut("execution(* com.meituan.hyt.test.service.*.*(..))")宣告一個切入點,可以攔截具體到某個方法,即在執行此方法之前、之後、最終、異常……時可以執行的其他業務方法(通知advice);
括號內的意思是:攔截某個方法,返回值是所有型別(第一個*),要攔截的是com.aoptest.service包及其子包下的所有類(..*)類下所有的方法(第三個.*)

2、args(name)
可以得到引數值,此時args(name)限制條件限定了"eexecution(* com.meituan.hyt.test.service.*.*(..))"中只攔截引數個數只有1個且型別為String的方法,而不是所有方法


5、編寫測試方法

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.meituan.hyt.test.service.PersonService;

/**
 * Created by heyutao on 15/11/2.
 */
public class Main {
    public static void main(String[] args) {
        ApplicationContext cxt = new ClassPathXmlApplicationContext("applicationContext.xml");
        PersonService personService = (PersonService) cxt.getBean("personService");

        System.out.println("----------------save start------------");
        personService.save("我是引數");
        System.out.println("----------------save end------------");


        System.out.println("----------------update start------------");
        personService.update(100);
        System.out.println("----------------update end------------");


        System.out.println("----------------throwException start------------");
        personService.throwException();
        System.out.println("----------------throwException end------------");


        System.out.println("----------------getPersonName start------------");
        String result = personService.getPersonName();
        System.out.println(result);
        System.out.println("----------------getPersonName end------------");
    }
}

6、執行結果

----------------save start------------
進入方法---環繞通知
前置通知
---我是引數---
我是save()方法。。。
退出方法---環繞通知
最終通知
後置通知
---null---
----------------save end------------
----------------update start------------
進入方法---環繞通知
我是update()方法。。。
退出方法---環繞通知
最終通知
後置通知
---null---
----------------update end------------
----------------throwException start------------
進入方法---環繞通知
我是throwException()方法。。。
最終通知
例外通知
異常了。。
Exception in thread "main" java.lang.RuntimeException: 異常了。。
    at com.meituan.hyt.test.service.PersonServiceImpl.throwException(PersonServiceImpl.java:32)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:80)
    at com.meituan.hyt.test.aop.MyInterceptor.doAround(MyInterceptor.java:51)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:621)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:610)
    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:65)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.aspectj.AspectJAfterAdvice.invoke(AspectJAfterAdvice.java:42)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:51)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:55)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at com.sun.proxy.$Proxy12.throwException(Unknown Source)
    at Main.main(Main.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)

    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

二、原理分析

1、名稱空間

<aop:aspectj-autoproxy proxy-target-class="true"> 該名稱空間會交給org.springframework.aop.config.AopNamespaceHandler處理,並在AspectJAutoProxyBeanDefinitionParser中,會執行parse方法解析配置:

public BeanDefinition parse(Element element, ParserContext parserContext) {  
    AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(parserContext, element);  
    extendBeanDefinition(element, parserContext);  
    return null;  
}  
其中AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(parserContext, element);目的是註冊AnnotationAwareAspectJAutoProxyCreator:
if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {  
    BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);  
    if (!cls.getName().equals(apcDefinition.getBeanClassName())) {  
        int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName());  
        int requiredPriority = findPriorityForClass(cls);  
        if (currentPriority < requiredPriority) {  
            apcDefinition.setBeanClassName(cls.getName());  
        }  
    }  
    return null;  
}  
即首先判斷當前容器中是否包含名字為AUTO_PROXY_CREATOR_BEAN_NAME的Bean, 如果包含:然後判斷優先順序,誰優先順序高誰獲勝,即最後那個獲勝的是實際的AutoProxyCreator。到此我們可以看到跟使用xml配置的方式 "<bean class="org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator">"配置沒什麼區別,除了沒有名字外。

2、AspectJAwareAdvisorAutoProxyCreator

AspectJAwareAdvisorAutoProxyCreator的註冊,對於AOP的實現基本就靠這個類實現。AspectJAwareAdvisorAutoProxyCreator實現了SmartInstantiationAwareBeanPostProcessor這個介面,它是BeanPostProcessor的子介面。
BeanPostProcessor介面作用是:如果這個介面的某個實現類被註冊到某個容器,那麼spring容器的每個受管Bean在呼叫初始化方法之前,都會獲得該介面實現類的一個回撥,回撥方法包括postProcessBeforeInstantiation以及postProcessAfterInstantiation方法。AspectJAwareAdvisorAutoProxyCreator的實現原理就是在回撥方法中,找到所有的標有@AspectJ類中的增加方法,即標有@Before,@After,@AfterReturning,@Around等註解的方法,並且從中挑出能cut到當前bean的advisor,一個增強方法對應Advisor,最終形成一個Advisor的列表,並且是有序的集合,順序分別是Around, Before, After, AfterReturning, AfterThrowing。然後將這個Advisor的列表作為引數,生成目標物件的代理物件,並返回。動態生成代理物件的方式有兩種:jdk動態代理和cglib。具體請參考http://blog.csdn.net/heyutao007/article/details/49738887