应用Spring的注解方式实现AOP

一、使用实例


1、导入需要的包

首先,为了使用Spring的AOP注解功能,必须在pom.xml中导入如下几个包。

[html]  view plain copy print ?
  1. <properties>  
  2.         <org.springframework-version>3.2.9.RELEASE</org.springframework-version>  
  3.         <commons-logging.version>1.1</commons-logging.version>  
  4.         <org.slf4j-version>1.7.2</org.slf4j-version>  
  5.     </properties>  
  6.   
  7.   
  8.     <dependencies>  
  9.         <!-- Spring -->  
  10.         <dependency>  
  11.             <groupId>org.springframework</groupId>  
  12.             <artifactId>spring-context</artifactId>  
  13.             <version>${org.springframework-version}</version>  
  14.             <exclusions>  
  15.                 <!-- Exclude Commons Logging in favor of SLF4j -->  
  16.                 <exclusion>  
  17.                     <groupId>commons-logging</groupId>  
  18.                     <artifactId>commons-logging</artifactId>  
  19.                 </exclusion>  
  20.             </exclusions>  
  21.         </dependency>  
  22.         <dependency>  
  23.             <groupId>org.springframework</groupId>  
  24.             <artifactId>spring-webmvc</artifactId>  
  25.             <version>${org.springframework-version}</version>  
  26.         </dependency>  
  27.         <dependency>  
  28.             <groupId>org.springframework</groupId>  
  29.             <artifactId>spring-test</artifactId>  
  30.             <version>${org.springframework-version}</version>  
  31.             <scope>test</scope>  
  32.         </dependency>  
  33.         <dependency>  
  34.             <groupId>org.springframework</groupId>  
  35.             <artifactId>spring-context-support</artifactId>  
  36.             <version>${org.springframework-version}</version>  
  37.         </dependency>  
  38.         <dependency>  
  39.             <groupId>org.springframework</groupId>  
  40.             <artifactId>spring-aop</artifactId>  
  41.             <version>${org.springframework-version}</version>  
  42.         </dependency>  
  43.         <dependency>  
  44.             <groupId>org.springframework</groupId>  
  45.             <artifactId>spring-orm</artifactId>  
  46.             <version>${org.springframework-version}</version>  
  47.         </dependency>  
  48.         <dependency>  
  49.             <groupId>org.springframework</groupId>  
  50.             <artifactId>spring-web</artifactId>  
  51.             <version>${org.springframework-version}</version>  
  52.         </dependency>  
  53.         <dependency>  
  54.             <groupId>org.dbunit</groupId>  
  55.             <artifactId>dbunit</artifactId>  
  56.             <version>2.4.6</version>  
  57.             <scope>test</scope>  
  58.         </dependency>  
  59.         <dependency>  
  60.             <groupId>org.springframework</groupId>  
  61.             <artifactId>spring-jdbc</artifactId>  
  62.             <version>${org.springframework-version}</version>  
  63.             <exclusions>  
  64.                 <!-- Exclude Commons Logging in favor of SLF4j -->  
  65.                 <exclusion>  
  66.                     <groupId>commons-logging</groupId>  
  67.                     <artifactId>commons-logging</artifactId>  
  68.                 </exclusion>  
  69.             </exclusions>  
  70.         </dependency>  
  71.   
  72.         <dependency>  
  73.             <groupId>commons-logging</groupId>  
  74.             <artifactId>commons-logging</artifactId>  
  75.             <version>${commons-logging.version}</version>  
  76.         </dependency>  
  77.   
  78.   
  79.         <!-- Logging -->  
  80.         <dependency>  
  81.             <groupId>org.slf4j</groupId>  
  82.             <artifactId>slf4j-api</artifactId>  
  83.             <version>${org.slf4j-version}</version>  
  84.         </dependency>  
  85.         <dependency>  
  86.             <groupId>log4j</groupId>  
  87.             <artifactId>log4j</artifactId>  
  88.             <version>1.2.15</version>  
  89.             <exclusions>  
  90.                 <exclusion>  
  91.                     <groupId>javax.mail</groupId>  
  92.                     <artifactId>mail</artifactId>  
  93.                 </exclusion>  
  94.                 <exclusion>  
  95.                     <groupId>javax.</groupId>  
  96.                     <artifactId>jms</artifactId>  
  97.                 </exclusion>  
  98.                 <exclusion>  
  99.                     <groupId>com.sun.jdmk</groupId>  
  100.                     <artifactId>jmxtools</artifactId>  
  101.                 </exclusion>  
  102.                 <exclusion>  
  103.                     <groupId>com.sun.jmx</groupId>  
  104.                     <artifactId>jmxri</artifactId>  
  105.                 </exclusion>  
  106.             </exclusions>  
  107.             <scope>runtime</scope>  
  108.         </dependency>  
  109.   
  110.   
  111.         <dependency>  
  112.             <groupId>org.aspectj</groupId>  
  113.             <artifactId>aspectjrt</artifactId>  
  114.             <version>1.6.11</version>  
  115.         </dependency>  
  116.         <dependency>  
  117.             <groupId>org.aspectj</groupId>  
  118.             <artifactId>aspectjweaver</artifactId>  
  119.             <version>1.6.11</version>  
  120.         </dependency>  
  121.   
  122.         <dependency>  
  123.             <groupId>cglib</groupId>  
  124.             <artifactId>cglib</artifactId>  
  125.             <version>2.1</version>  
  126.         </dependency>  
  127.     </dependencies>  


2、配置文件applicationContext.xml

[html]  view plain copy print ?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <beans xmlns="http://www.springframework.org/schema/beans"  
  4.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.        xmlns:aop="http://www.springframework.org/schema/aop"  
  6.        xmlns:context="http://www.springframework.org/schema/context"  
  7.        xsi:schemaLocation="http://www.springframework.org/schema/beans  
  8.        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
  9.        <span style="color:#FF0000;">http://www.springframework.org/schema/aop  
  10.        http://www.springframework.org/schema/aop/spring-aop-2.5.xsd</span>  
  11.        http://www.springframework.org/schema/context  
  12.        http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  13.   
  14.   
  15.     <!-- 声明注解方式加载bean-->  
  16.     <context:annotation-config/>  
  17.   
  18.     <!-- 要加载的bean的包路径-->  
  19.     <context:component-scan base-package="com.meituan.hyt.test.service"/>  
  20.   
  21.     <!-- 自动扫描被@Aspect注解的bean-->  
  22.     <aop:aspectj-autoproxy/>  
  23.   
  24.     <bean id="myInterceptor" class="com.meituan.hyt.test.aop.MyInterceptor"/>  
  25. </beans>  


3、编写自己的业务接口和实现类,注解为spring bean

[java]  view plain copy print ?
  1. package com.meituan.hyt.test.service;  
  2.   
  3. public interface PersonService {  
  4.     public void save(String name);  
  5.   
  6.     public void update(int name);  
  7.   
  8.     public void throwException();  
  9.   
  10.     public String getPersonName();  
  11.   
  12. }  

[java]  view plain copy print ?
  1. package com.meituan.hyt.test.service;  
  2.   
  3. import org.springframework.stereotype.Service;  
  4.   
  5. @Service(value = "personService")  
  6. public class PersonServiceImpl implements PersonService {  
  7.   
  8.     @Override  
  9.     public String getPersonName() {  
  10.         System.out.println("我是getPersonName()方法。。。");  
  11.         return "返回结果";  
  12.     }  
  13.   
  14.   
  15.     @Override  
  16.     public void save(String name) {  
  17.         System.out.println("我是save()方法。。。");  
  18.     }  
  19.   
  20.     @Override  
  21.     public void update(int name) {  
  22.         System.out.println("我是update()方法。。。");  
  23.     }  
  24.   
  25.     @Override  
  26.     public void throwException() {  
  27.         System.out.println("我是throwException()方法。。。");  
  28.         throw new RuntimeException("异常了。。");  
  29.     }  
  30. }  

4、编写切面

[java]  view plain copy print ?
  1. package com.meituan.hyt.test.aop;  
  2.   
  3. import org.aspectj.lang.ProceedingJoinPoint;  
  4. import org.aspectj.lang.annotation.*;  
  5.   
  6. /** 
  7.  * Created by heyutao on 15/11/2. 
  8.  */  
  9. @Aspect  
  10. public class MyInterceptor {  
  11.     @Pointcut("execution(* com.meituan.hyt.test.service.*.*(..))")  
  12.   
  13.     //声明一个切入点  
  14.     private void anyMethod() {  
  15.     }  
  16.   
  17.     @Before("anyMethod() && args(name)")//声明前置通知  
  18.     public void doBefore(String name) {  
  19.         System.out.println("前置通知");  
  20.         System.out.println("---" + name + "---");  
  21.     }  
  22.   
  23.     @AfterReturning(pointcut = "anyMethod()", returning = "result")//声明后置通知  
  24.     public void doAfterReturning(String result) {  
  25.         System.out.println("后置通知");  
  26.         System.out.println("---" + result + "---");  
  27.     }  
  28.   
  29.     @AfterThrowing(pointcut = "anyMethod()", throwing = "e")//声明例外通知  
  30.     public void doAfterThrowing(Exception e) {  
  31.         System.out.println("例外通知");  
  32.         System.out.println(e.getMessage());  
  33.     }  
  34.   
  35.     @After("anyMethod()")//声明最终通知  
  36.     public void doAfter() {  
  37.         System.out.println("最终通知");  
  38.     }  
  39.   
  40.     @Around("anyMethod()")//声明环绕通知  
  41.     public Object doAround(ProceedingJoinPoint pjp) throws Throwable {  
  42.         System.out.println("进入方法---环绕通知");  
  43.         //显示调用,确保被代理的方法被调用  
  44.         Object o = pjp.proceed();  
  45.         System.out.println("退出方法---环绕通知");  
  46.         return o;  
  47.     }  
  48. }  

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、编写测试方法

[java]  view plain copy print ?
  1. import org.springframework.context.ApplicationContext;  
  2. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  3. import com.meituan.hyt.test.service.PersonService;  
  4.   
  5. /** 
  6.  * Created by heyutao on 15/11/2. 
  7.  */  
  8. public class Main {  
  9.     public static void main(String[] args) {  
  10.         ApplicationContext cxt = new ClassPathXmlApplicationContext("applicationContext.xml");  
  11.         PersonService personService = (PersonService) cxt.getBean("personService");  
  12.   
  13.         System.out.println("----------------save start------------");  
  14.         personService.save("我是参数");  
  15.         System.out.println("----------------save end------------");  
  16.   
  17.   
  18.         System.out.println("----------------update start------------");  
  19.         personService.update(100);  
  20.         System.out.println("----------------update end------------");  
  21.   
  22.   
  23.         System.out.println("----------------throwException start------------");  
  24.         personService.throwException();  
  25.         System.out.println("----------------throwException end------------");  
  26.   
  27.   
  28.         System.out.println("----------------getPersonName start------------");  
  29.         String result = personService.getPersonName();  
  30.         System.out.println(result);  
  31.         System.out.println("----------------getPersonName end------------");  
  32.     }  
  33. }  

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方法解析配置:

[java]  view plain copy print ?
  1. public BeanDefinition parse(Element element, ParserContext parserContext) {    
  2.     AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(parserContext, element);    
  3.     extendBeanDefinition(element, parserContext);    
  4.     return null;    
  5. }    
其中AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(parserContext, element);目的是注册AnnotationAwareAspectJAutoProxyCreator:

[java]  view plain copy print ?
  1. if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {    
  2.     BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);    
  3.     if (!cls.getName().equals(apcDefinition.getBeanClassName())) {    
  4.         int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName());    
  5.         int requiredPriority = findPriorityForClass(cls);    
  6.         if (currentPriority < requiredPriority) {    
  7.             apcDefinition.setBeanClassName(cls.getName());    
  8.         }    
  9.     }    
  10.     return null;    
  11. }    

即首先判断当前容器中是否包含名字为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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值