应用Spring的注解方式实现AOP
来源:互联网 发布:java replace多个字符 编辑:程序博客网 时间:2024/05/22 10:35
一、使用实例
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. */@Aspectpublic 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
- 应用Spring的注解方式实现AOP
- 应用Spring的注解方式实现AOP
- 使用Spring的注解方式实现AOP
- 使用Spring的注解方式实现AOP
- 使用Spring的注解方式实现AOP
- Spring使用注解的方式实现AOP
- 使用Spring的注解方式实现AOP
- 使用Spring的注解方式实现AOP
- 使用Spring的注解方式实现AOP
- 使用Spring的注解方式实现AOP
- 注解方式实现Spring的aop
- 使用Spring的注解方式实现AOP
- 使用Spring的注解方式实现AOP
- Spring 注解方式实现的AOP
- 使用Spring的注解方式实现AOP
- 使用Spring的注解方式实现AOP
- Spring 注解方式实现的AOP
- 使用Spring的注解方式实现AOP
- 关于困觉
- C# 拷贝文件到另一个目录
- 自定义控件之时钟
- kafka安装测试
- JavaScript
- 应用Spring的注解方式实现AOP
- spring的事务传播属性与数据库的隔离级别
- Android性能优化典范
- SQL Server 损坏修复 之三 不同部位损坏的应对
- SOJ 2505 The Country Fair
- java自定义注解及注解使用
- iOS 应用内跳转到系统设置
- 模板方法模式深度解析(二)
- android_internal_storage