(转)Spring AOP编程原理、Demo

转自:

http://pandonix.iteye.com/blog/336873/

Spring AOP 详解

此前对于AOP的使用仅限于声明式事务,除此之外在实际开发中也没有遇到过与之相关的问题。最近项目中遇到了以下几点需求,仔细思考之后,觉得采用AOP 来解决。一方面是为了以更加灵活的方式来解决问题,另一方面是借此机会深入学习Spring AOP相关的内容。本文是权当本人的自己AOP学习笔记,以下需求不用AOP肯定也能解决,至于是否牵强附会,仁者见仁智者见智。

  1. 对部分函数的调用进行日志记录,用于观察特定问题在运行过程中的函数调用情况
  2. 监控部分重要函数,若抛出指定的异常,需要以短信或邮件方式通知相关人员
  3. 金控部分重要函数的执行时间

事实上,以上需求没有AOP也能搞定,只是在实现过程中比较郁闷摆了。

  1. 需要打印日志的函数分散在各个包中,只能找到所有的函数体,手动添加日志。然而这些日志都是临时的,待问题解决之后应该需要清除打印日志的代码,只能再次手动清除^_^!
  2. 类 似1的情况,需要捕获异常的地方太多,如果手动添加时想到很可能明天又要手动清除,只能再汗。OK,该需求相对比较固定,属于长期监控的范畴,并不需求临 时添加后再清除。然而,客户某天要求,把其中20%的异常改为短信提醒,剩下的80%改用邮件提醒。改之,两天后,客户抱怨短信太多,全部改成邮件提 醒...
  3. 该需求通常用于监控某些函数的执行时间,用以判断系统执行慢的瓶颈所在。瓶颈被解决之后,烦恼同情况1

终于下定决心,采用AOP来解决!代码如下:

切面类TestAspect

Java代码  

  1. package com.spring.aop;
  2. /**
  3. * 切面
  4. *
  5. */
  6. public class TestAspect {
  7. public void doAfter(JoinPoint jp) {
  8. System.out.println("log Ending method: "
  9. + jp.getTarget().getClass().getName() + "."
  10. + jp.getSignature().getName());
  11. }
  12. public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
  13. long time = System.currentTimeMillis();
  14. Object retVal = pjp.proceed();
  15. time = System.currentTimeMillis() - time;
  16. System.out.println("process time: " + time + " ms");
  17. return retVal;
  18. }
  19. public void doBefore(JoinPoint jp) {
  20. System.out.println("log Begining method: "
  21. + jp.getTarget().getClass().getName() + "."
  22. + jp.getSignature().getName());
  23. }
  24. public void doThrowing(JoinPoint jp, Throwable ex) {
  25. System.out.println("method " + jp.getTarget().getClass().getName()
  26. + "." + jp.getSignature().getName() + " throw exception");
  27. System.out.println(ex.getMessage());
  28. }
  29. private void sendEx(String ex) {
  30. //TODO 发送短信或邮件提醒
  31. }
  32. }

Java代码  

  1. package com.spring.service;
  2. /**
  3. * 接口A
  4. */
  5. public interface AService {
  6. public void fooA(String _msg);
  7. public void barA();
  8. }

Java代码  

  1. package com.spring.service;
  2. /**
  3. *接口A的实现类
  4. */
  5. public class AServiceImpl implements AService {
  6. public void barA() {
  7. System.out.println("AServiceImpl.barA()");
  8. }
  9. public void fooA(String _msg) {
  10. System.out.println("AServiceImpl.fooA(msg:"+_msg+")");
  11. }
  12. }

Java代码  

  1. package com.spring.service;
  2. /**
  3. *   Service类B
  4. */
  5. public class BServiceImpl {
  6. public void barB(String _msg, int _type) {
  7. System.out.println("BServiceImpl.barB(msg:"+_msg+" type:"+_type+")");
  8. if(_type == 1)
  9. throw new IllegalArgumentException("测试异常");
  10. }
  11. public void fooB() {
  12. System.out.println("BServiceImpl.fooB()");
  13. }
  14. }

ApplicationContext

Java代码  

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xsi:schemaLocation="
  6. http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  8. http://www.springframework.org/schema/aop
  9. http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
  10. default-autowire="autodetect">
  11. <aop:config>
  12. <aop:aspect id="TestAspect" ref="aspectBean">
  13. <!--配置com.spring.service包下所有类或接口的所有方法-->
  14. <aop:pointcut id="businessService"
  15. expression="execution(* com.spring.service.*.*(..))" />
  16. <aop:before pointcut-ref="businessService" method="doBefore"/>
  17. <aop:after pointcut-ref="businessService" method="doAfter"/>
  18. <aop:around pointcut-ref="businessService" method="doAround"/>
  19. <aop:after-throwing pointcut-ref="businessService" method="doThrowing" throwing="ex"/>
  20. </aop:aspect>
  21. </aop:config>
  22. <bean id="aspectBean" class="com.spring.aop.TestAspect" />
  23. <bean id="aService" class="com.spring.service.AServiceImpl"></bean>
  24. <bean id="bService" class="com.spring.service.BServiceImpl"></bean>
  25. </beans>

测试类AOPTest

Java代码  

  1. public class AOPTest extends AbstractDependencyInjectionSpringContextTests {
  2. private AService aService;
  3. private BServiceImpl bService;
  4. protected String[] getConfigLocations() {
  5. String[] configs = new String[] { "/applicationContext.xml"};
  6. return configs;
  7. }
  8. /**
  9. * 测试正常调用
  10. */
  11. public void testCall()
  12. {
  13. System.out.println("SpringTest JUnit test");
  14. aService.fooA("JUnit test fooA");
  15. aService.barA();
  16. bService.fooB();
  17. bService.barB("JUnit test barB",0);
  18. }
  19. /**
  20. * 测试After-Throwing
  21. */
  22. public void testThrow()
  23. {
  24. try {
  25. bService.barB("JUnit call barB",1);
  26. } catch (IllegalArgumentException e) {
  27. }
  28. }
  29. public void setAService(AService service) {
  30. aService = service;
  31. }
  32. public void setBService(BServiceImpl service) {
  33. bService = service;
  34. }
  35. }

运行结果如下:

Java代码  

  1. log Begining method: com.spring.service.AServiceImpl.fooA
  2. AServiceImpl.fooA(msg:JUnit test fooA)
  3. log Ending method: com.spring.service.AServiceImpl.fooA
  4. process time: 0 ms
  5. log Begining method: com.spring.service.AServiceImpl.barA
  6. AServiceImpl.barA()
  7. log Ending method: com.spring.service.AServiceImpl.barA
  8. process time: 0 ms
  9. log Begining method: com.spring.service.BServiceImpl.fooB
  10. BServiceImpl.fooB()
  11. log Ending method: com.spring.service.BServiceImpl.fooB
  12. process time: 0 ms
  13. log Begining method: com.spring.service.BServiceImpl.barB
  14. BServiceImpl.barB(msg:JUnit test barB type:0)
  15. log Ending method: com.spring.service.BServiceImpl.barB
  16. process time: 0 ms
  17. log Begining method: com.spring.service.BServiceImpl.barB
  18. BServiceImpl.barB(msg:JUnit call barB type:1)
  19. log Ending method: com.spring.service.BServiceImpl.barB
  20. method com.spring.service.BServiceImpl.barB throw exception
  21. 测试异常

《Spring参考手册》中定义了以下几个AOP的重要概念,结合以上代码分析如下:

  • 切面(Aspect) :官方的抽象定义为“一个关注点的模块化,这个关注点可能会横切多个对象”,在本例中,“切面”就是类TestAspect所关注的具体行为,例如,AServiceImpl.barA()的调用就是切面TestAspect所关注的行为之一。“切面”在ApplicationContext中<aop:aspect>来配置。
  • 连接点(Joinpoint) :程序执行过程中的某一行为,例如,AServiceImpl.barA()的调用或者BServiceImpl.barB(String _msg, int _type)抛出异常等行为。
  • 通知(Advice) :“切面”对于某个“连接点”所产生的动作,例如,TestAspect中对com.spring.service包下所有类的方法进行日志记录的动作就是一个Advice。其中,一个“切面”可以包含多个“Advice”,例如TestAspect
  • 切入点(Pointcut) :匹配连接点的断言,在AOP中通知和一个切入点表达式关联。例如,TestAspect中的所有通知所关注的连接点,都由切入点表达式execution(* com.spring.service.*.*(..))来决定
  • 目标对象(Target Object) :被一个或者多个切面所通知的对象。例如,AServcieImpl和BServiceImpl,当然在实际运行时,Spring AOP采用代理实现,实际AOP操作的是TargetObject的代理对象。
  • AOP代理(AOP Proxy) 在Spring AOP中有两种代理方式,JDK动态代理和CGLIB代理。默认情况下,TargetObject实现了接口时,则采用JDK动态代理,例如,AServiceImpl;反之,采用CGLIB代理,例如,BServiceImpl。强制使用CGLIB代理需要将 <aop:config> 的 proxy-target-class 属性设为true

通知(Advice)类型

  • 前置通知(Before advice) :在某连接点(JoinPoint)之前执行的通知,但这个通知不能阻止连接点前的执行。ApplicationContext中在<aop:aspect>里面使用<aop:before>元素进行声明。例如,TestAspect中的doBefore方法
  • 后通知(After advice) :当某连接点退出的时候执行的通知(不论是正常返回还是异常退出)。ApplicationContext中在<aop:aspect>里面使用<aop:after>元素进行声明。例如,TestAspect中的doAfter方法,所以AOPTest中调用BServiceImpl.barB抛出异常时,doAfter方法仍然执行
  • 返回后通知(After return advice) :在某连接点正常完成后执行的通知,不包括抛出异常的情况。ApplicationContext中在<aop:aspect>里面使用<after-returning>元素进行声明。
  • 环绕通知(Around advice) :包围一个连接点的通知,类似Web中Servlet规范中的Filter的doFilter方法。可以在方法的调用前后完成自定义的行为,也可以选择不执行。ApplicationContext中在<aop:aspect>里面使用<aop:around>元素进行声明。例如,TestAspect中的doAround方法。
  • 抛出异常后通知(After throwing advice) : 在方法抛出异常退出时执行的通知。 ApplicationContext中在<aop:aspect>里面使用<aop:after-throwing>元素进行声明。例如,TestAspect中的doThrowing方法。

切入点表达式

  • 通常情况下,表达式中使用”execution“就可以满足大部分的要求。表达式格式如下:

Java代码  

  1. execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)

modifiers-pattern:方法的操作权限

ret-type-pattern:返回值

declaring-type-pattern:方法所在的包

name-pattern:方法名

parm-pattern:参数名

throws-pattern:异常

其中,除ret-type-pattern和name-pattern之外,其他都是可选的。上例中,execution(* com.spring.service.*.*(..))表示com.spring.service包下,返回值为任意类型;方法名任意;参数不作限制的所有方法。

  • 通知参数

可以通过args来绑定参数,这样就可以在通知(Advice)中访问具体参数了。例如,<aop:aspect>配置如下

Java代码  

  1. <aop:config>
  2. <aop:aspect id="TestAspect" ref="aspectBean">
  3. <aop:pointcut id="businessService"
  4. expression="execution(* com.spring.service.*.*(String,..)) and args(msg,..)" />
  5. <aop:after pointcut-ref="businessService" method="doAfter"/>
  6. </aop:aspect>
  7. </aop:config>

TestAspect的doAfter方法中就可以访问msg参数,但这样以来AService中的barA()和BServiceImpl中的barB()就不再是连接点,因为execution(* com.spring.service.*.*(String,..))只配置第一个参数为String类型的方法。其中,doAfter方法定义如下:

Java代码  

  1. public void doAfter(JoinPoint jp,String msg)
  • 访问当前的连接点

任何通知(Advice)方法可以将第一个参数定义为 org.aspectj.lang.JoinPoint 类型。JoinPoint 接口提供了一系列有用的方法, 比如 getArgs() (返回方法参数)、getThis() (返回代理对象)、getTarget() (返回目标)、getSignature() (返回正在被通知的方法相关信息)和 toString()(打印出正在被通知的方法的有用信息。

时间: 2024-07-31 14:27:29

(转)Spring AOP编程原理、Demo的相关文章

Spring Aop编程的demo

1: 新建一个普通的bean :Role 属性 Id,name,添加无参构造,setter getter方法 2:新建一个接口:RoleService,随便写一个方法printRole 3:新建一个类RoleServiceImpl,实现RoleService接口,重写printRole方法 注意 @Component 注解别忘了 4:定义切面类 RoleAspect 添加四个通知方法 注意: 添加@Aspect注解 execution中的参数一定要写对,例:"execution(* aop.se

Spring AOP 实现原理(二) 使用 Spring AOP

与 AspectJ 相同的是,Spring AOP 同样需要对目标类进行增强,也就是生成新的 AOP 代理类:与 AspectJ 不同的是,Spring AOP 无需使用任何特殊 命令对 Java 源代码进行编译,它采用运行时动态地.在内存中临时生成"代理类"的方式来生成 AOP 代理. Spring 允许使用 AspectJ Annotation 用于定义方面(Aspect).切入点(Pointcut)和增强处理(Advice),Spring 框架则可识别并根据这些 Annotati

Spring AOP底层原理

------------------siwuxie095 Spring AOP 底层原理 AOP 即 Aspect Oriented Programming,面向切面编程, 即 不通过修改源代码的方式扩展功能 「在不修改源代码的情况下,对程序进行增强」 2.AOP 采取横向抽取机制,取代了传统纵向继承体系重复性 代码 3.AOP 底层原理所使用的技术 (1)JDK 的动态代理:针对实现了接口的类产生代理 即 有接口,使用动态代理创建接口实现类的代理对象 (2)CGLIB 的动态代理:针对没有实现

Spring AOP 实现原理与 CGLIB 应用--转

AOP(Aspect Orient Programming),作为面向对象编程的一种补充,广泛应用于处理一些具有横切性质的系统级服务,如事务管理.安全检查.缓存.对象池管理等.AOP 实现的关键就在于 AOP 框架自动创建的 AOP 代理,AOP 代理则可分为静态代理和动态代理两大类,其中静态代理是指使用 AOP 框架提供的命令进行编译,从而在编译阶段就可生成 AOP 代理类,因此也称为编译时增强:而动态代理则在运行时借助于 JDK 动态代理.CGLIB 等在内存中“临时”生成 AOP 动态代理

【转】Spring AOP 实现原理与 CGLIB 应用

AOP(Aspect Orient Programming),作为面向对象编程的一种补充,广泛应用于处理一些具有横切性质的系统级服务,如事务管理.安全检查.缓存.对象池管理等.AOP 实现的关键就在于 AOP 框架自动创建的 AOP 代理,AOP 代理则可分为静态代理和动态代理两大类,其中静态代理是指使用 AOP 框架提供的命令进行编译,从而在编译阶段就可生成 AOP 代理类,因此也称为编译时增强:而动态代理则在运行时借助于 JDK 动态代理.CGLIB 等在内存中"临时"生成 AOP

Spring AOP实现原理与CGLIB应用(转)

AOP(Aspect Orient Programming),作为面向对象编程的一种补充,广泛应用于处理一些具有横切性质的系统级服务,如事务管理.安全检查.缓存.对象池管理等.AOP 实现的关键就在于 AOP 框架自动创建的 AOP 代理,AOP 代理则可分为静态代理和动态代理两大类,其中静态代理是指使用 AOP 框架提供的命令进行编译,从而在编译阶段就可生成 AOP 代理类,因此也称为编译时增强:而动态代理则在运行时借助于 JDK 动态代理.CGLIB 等在内存中“临时”生成 AOP 动态代理

Spring aop 小实例demo

Hadoop从2.4.0版本开始支持hdfs的ACL,在CDH5.0当中也集成了该特性,下面对其进行一些测试: unnamed user (file owner) 文件的拥有者 unnamed group (file group) 文件的所属组 named user 除了文件的拥有者和拥有组之外,的其它用户 named group 除了文件的拥有者和拥有组之外,的其它用户 mask  权限掩码,用于过滤named user和named group的权限 一.启用ACL: <property>

循序渐进之Spring AOP(1) - 原理

AOP全称是Aspect Oriented Programing,通常译为面向切面编程.利用AOP可以对面向对象编程做很好的补充. 用生活中的改装车比喻,工厂用面向对象的方法制造好汽车后,车主往往有些个性化的想法,但是又不想对车进行大规模的拆卸.替换零件,这时可以买一些可替换的零件.装饰安装到汽车上,并且这些改装应该很容易拆卸,以避免验车时无法通过. 先看一个实际例子:有一个用户登录的方法,某一段时间内我们希望能够临时监控执行时间,但是又不想直接在方法上修改,用AOP方案实现如下. UserSe

Spring AOP应用实例demo

AOP(Aspect-Oriented Programming,面向方面编程),可以说是OOP(Object-OrientedPrograming,面向对象编程)的补充和完善.OOP引入封装.继承和多态性等概念来建立一种对象层次结构,用以模拟公共行为的一个集合. OOP的问题,AOP的补充 当我们需要为分散的对象引入公共行为的时候,OOP则显得无能为力.也就是说,OOP允许你定义从上到下的关系,但并不适合定义从左到右的关系.例如日志功能.日志代码往往水平地散布在所有对象层次中,而与它所散布到的对