spring AOP应用

转自:http://wb284551926.iteye.com/blog/1887650html

最近新项目要启动,在搭建项目基础架构的时候,想要加入日志功能和执行性能监控的功能,想了不少的想法,最后仍是想到用spring的aop功能,一是不须要写那么多的重复代码,二是灵活好用,好了如今就讲讲这个aop功能的使用。(须要的jar包:spring.jar、asm-2.2.3.jar、asm-commons-2.2.3.jar、aopalliance.jar、aspectjweaver.jar、cglib-nodep-2.1_3.jar,能够忽略版本号)java

1.创建一个切入类,包括doBefore、doAround、doAfter、doThrowing等方法。node

Java代码   收藏代码
  1. /***************************************** 
  2.  * @类名:com.util.TestAspect 
  3.  * @做者:王博 
  4.  * @时间:Jun 15, 2013 
  5.  * @版本:1.0 
  6.  * @描述: 
  7.  * @修改人员: 
  8.  * @修改时间: 
  9.  * @修改说明: 
  10.  *****************************************/  
  11. package com.util;  
  12.   
  13. import org.aspectj.lang.JoinPoint;  
  14. import org.aspectj.lang.ProceedingJoinPoint;  
  15.   
  16. public class TestAspect {  
  17.       public void doAfter(JoinPoint jp) {    
  18.             System.out.println("log Ending method: "    
  19.                     + jp.getTarget().getClass().getName() + "."    
  20.                     + jp.getSignature().getName());    
  21.         }    
  22.         
  23.         public Object doAround(ProceedingJoinPoint pjp) throws Throwable {    
  24.             long time = System.currentTimeMillis();    
  25.             Object retVal = pjp.proceed();    
  26.             time = System.currentTimeMillis() - time;    
  27.             System.out.println("process time: " + time + " ms");    
  28.             return retVal;    
  29.         }    
  30.         
  31.         public void doBefore(JoinPoint jp) {    
  32.             System.out.println("log Begining method: "    
  33.                     + jp.getTarget().getClass().getName() + "."    
  34.                     + jp.getSignature().getName());    
  35.         }    
  36.         
  37.         public void doThrowing(JoinPoint jp, Throwable ex) {    
  38.             System.out.println("method " + jp.getTarget().getClass().getName()    
  39.                     + "." + jp.getSignature().getName() + " throw exception");    
  40.             System.out.println(ex.getMessage());    
  41.         }   
  42. }  

 2.在spring的配置文件中加入aop配置,proxy-target-class="true"红色部分*注意*,不加入这个,action是拦截不到的,切记spring

com.neau.project.*.*.*.*(..))"  这里主要注意的是express

例如你的包结构是com.xxx.action.actionclass  你须要这样写才能拦截到 com.xxx.action.actionclass.*  架构

最后的.*是表明actionclass中的方法。下面有这个配置的具体说明模块化

若是要放行一些方法,好比get/set方法能够用 and 关键字,例如性能

execution(* com.neau.project.*.*.*.*(..)) and !execution(* com.neau.project.*.*.*.get*(..)) and !execution(* com.neau.project.*.*.*.set*(..))this

Xml代码   收藏代码
  1. <aop:config <span style="color: #ff0000;">proxy-target-class="true"</span>   
  2.        <aop:aspect id="TestAspect" ref="aspectBean">    
  3.            <!--配置com.neau.project.*.*.*.*包下全部类或接口的全部方法-->    
  4.            <aop:pointcut id="AOPService"    
  5.                expression="execution(* <span style="color: #ff0000;">com.neau.project.*.*.*.*</span>(..))" />              <aop:before pointcut-ref="AOPService" method="doBefore"/>    
  6.            <aop:after pointcut-ref="AOPService" method="doAfter"/>    
  7.            <aop:around pointcut-ref="AOPService" method="doAround"/>    
  8.            <aop:after-throwing pointcut-ref="AOPService" method="doThrowing" throwing="ex"/>    
  9.        </aop:aspect>    
  10.    </aop:config>    
  11.  <bean id="aspectBean" class="com.util.TestAspect" />    

 

3.启动项目,执行spa

访问action

Java代码   收藏代码
  1. log Begining method: com.neau.project.logon.action.LogonAction.test  
  2. 2013-06-16 15:31:56,737 - {pstm-100001} Executing Statement:    select count(*) from rdtteam t    
  3. 2013-06-16 15:31:56,737 - {pstm-100001} Parameters: []  
  4. 2013-06-16 15:31:56,737 - {pstm-100001} Types: []  
  5. 2013-06-16 15:31:56,749 - {pstm-100004} Executing Statement:    select t.* from rdtteam t limit ?,?     
  6. 2013-06-16 15:31:56,749 - {pstm-100004} Parameters: [0, 20]  
  7. 2013-06-16 15:31:56,749 - {pstm-100004} Types: [java.lang.Integer, java.lang.Integer]  
  8. log Ending method: com.neau.project.logon.action.LogonAction.test  
  9. process time: 261 ms  
  10. log Begining method: com.neau.project.logon.action.LogonAction.getRdtTeamPage  
  11. log Ending method: com.neau.project.logon.action.LogonAction.getRdtTeamPage  
  12. process time: 0 ms  
  13. log Begining method: com.neau.project.logon.action.LogonAction.get_rdtTeamList  
  14. log Ending method: com.neau.project.logon.action.LogonAction.get_rdtTeamList  
  15. process time: 0 ms  

 aop就这样实现了拦截action,简单吧,简单的工做实现大功能是我等苦逼开发者的目标。

 

偷点别的写好的吧。

 

《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()(打印出正在被通知的方法的有用信息。

 

warning no match for this type name: com.zrm.service [Xlint:invalidAbsoluteTypeName]

<aop:config>
   <!-- 切入点 -->
   <aop:pointcut id="gkServicePct" expression="execution(* com.zrm.service.*(..))" />
   <aop:advisor pointcut-ref="gkServicePct" advice-ref="gkTxAdvice" order="0" />
</aop:config>

出现warning no match for this type name: com.zrm.service [Xlint:invalidAbsoluteTypeName]错误

配置事务时,必定注意expression="execution(* com.zrm.service.*(..))" 应该为

expression="execution(* com.zrm.service.*.*(..))" ,这样,切点才定位到方法上了。

 

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

感谢:http://hi.baidu.com/gglzf4/item/a58624e2f962d113585dd832

感谢:http://bbs.csdn.net/topics/350180595    11楼的同志

感谢:http://blog.sina.com.cn/s/blog_5f53615f0101ijdl.html

 

看了那么童鞋的经验让我少走了很多弯路,看来我就是吃百家饭长大孩纸的命,伤不起啊。苦逼的开发者伤不起啊。