Aop详解与实例

来源:互联网 发布:java对象和json的转换 编辑:程序博客网 时间:2024/05/01 20:04
  1. SPRING AOP 概念解析以及例子示范   
  2.   先了解AOP的相关术语:   
  3. 1.通知(Advice):   
  4. 通知定义了切面是什么以及何时使用。描述了切面要完成的工作和何时需要执行这个工作。   
  5. 2.连接点(Joinpoint):   
  6. 程序能够应用通知的一个“时机”,这些“时机”就是连接点,例如方法被调用时、异常被抛出时等等。   
  7. 3.切入点(Pointcut)   
  8. 通知定义了切面要发生的“故事”和时间,那么切入点就定义了“故事”发生的地点,例如某个类或方法的名称,Spring中允许我们方便的用正则表达式来指定   
  9. 4.切面(Aspect)   
  10. 通知和切入点共同组成了切面:时间、地点和要发生的“故事”   
  11. 5.引入(Introduction)   
  12. 引入允许我们向现有的类添加新的方法和属性(Spring提供了一个方法注入的功能)   
  13. 6.目标(Target)   
  14. 即被通知的对象,如果没有AOP,那么它的逻辑将要交叉别的事务逻辑,有了AOP之后它可以只关注自己要做的事(AOP让他做爱做的事)   
  15. 7.代理(proxy)   
  16. 应用通知的对象,详细内容参见设计模式里面的代理模式   
  17. 8.织入(Weaving)   
  18. 把切面应用到目标对象来创建新的代理对象的过程,织入一般发生在如下几个时机:   
  19. (1)编译时:当一个类文件被编译时进行织入,这需要特殊的编译器才可以做的到,例如AspectJ的织入编译器   
  20. (2)类加载时:使用特殊的ClassLoader在目标类被加载到程序之前增强类的字节代码   
  21. (3)运行时:切面在运行的某个时刻被织入,SpringAOP就是以这种方式织入切面的,原理应该是使用了JDK的动态代理技术   
  22.   
  23. Spring提供了4种实现AOP的方式:   
  24. 1.经典的基于代理的AOP   
  25. 2.@AspectJ注解驱动的切面   
  26. 3.纯POJO切面   
  27. 4.注入式AspectJ切面   
  28.   
  29. 首先看经典的基于代理的AOP:   
  30. Spring支持五种类型的通知:   
  31. Before(前)  org.apringframework.aop.MethodBeforeAdvice   
  32. After-returning(返回后) org.springframework.aop.AfterReturningAdvice   
  33. After-throwing(抛出后) org.springframework.aop.ThrowsAdvice   
  34. Arround(周围) org.aopaliance.intercept.MethodInterceptor   
  35. Introduction(引入) org.springframework.aop.IntroductionInterceptor   
  36.   
  37. 值的说明的是周围通知,他是由AOP Alliance中的接口定义的而非Spring,周围通知相当于前通知、返回后通知、抛出后通知的结合(传说中的完全体?好吧,我看日和看多   
  38.   
  39. 了)还有引入通知怎么玩我还没搞清楚,等心无杂念的时候玩玩   
  40.   
  41. 这东西怎么玩?这么几个步骤:   
  42. 1.创建通知:实现这几个接口,把其中的方法实现了   
  43. 2.定义切点和通知者:在Spring配制文件中配置这些信息   
  44. 3.使用ProxyFactoryBean来生成代理   
  45.   
  46. 具体做法。。。大晚上的就举个睡觉的例子吧:   
  47.   
  48. 首先写一个接口叫Sleepable,这是一个牛X的接口,所有具有睡觉能力的东西都可以实现该接口(不光生物,包括关机选项里面的休眠)   
  49.   
  50. package test.spring.aop.bean   
  51.   
  52. public interface Sleepable{   
  53.     
  54.     void sleep();    
  55. }   
  56.   
  57. 然后写一个Human类,他实现了这个接口   
  58.   
  59. package test.spring.aop.bean   
  60.   
  61. public Human implements Sleepable{   
  62.       
  63.    /*这人莫非跟寡人差不多?  
  64.     *除了睡觉睡的比较好之外其余的什么也不会做?*/  
  65.    public void sleep(){   
  66.       System.out.println("睡觉了!梦中自有颜如玉!");   
  67.    }   
  68.   
  69. }   
  70.   
  71.   
  72. 好了,这是主角,不过睡觉前后要做些辅助工作的,最基本的是脱穿衣服,失眠的人还要吃安眠药什么的,但是这些动作与纯粹的睡觉这一“业务逻辑”是不相干的,如果把   
  73.   
  74. 这些代码全部加入到sleep方法中,是不是有违单一职责呢?,这时候我们就需要AOP了。   
  75.   
  76. 编写一个SleepHelper类,它里面包含了睡觉的辅助工作,用AOP术语来说它就应该是通知了,我们需要实现上面的接口   
  77.   
  78. package test.spring.aop.bean;   
  79.   
  80. import java.lang.reflect.Method;   
  81.   
  82. import org.springframework.aop.AfterReturningAdvice;   
  83. import org.springframework.aop.MethodBeforeAdvice;   
  84.   
  85. public class SleepHelper implements MethodBeforeAdvice,AfterReturningAdvice{   
  86.   
  87.     public void before(Method mtd, Object[] arg1, Object arg2)   
  88.             throws Throwable {   
  89.         System.out.println("通常情况下睡觉之前要脱衣服!");   
  90.     }   
  91.   
  92.     public void afterReturning(Object arg0, Method arg1, Object[] arg2,   
  93.             Object arg3) throws Throwable {   
  94.         System.out.println("起床后要先穿衣服!");   
  95.     }   
  96.        
  97. }   
  98.   
  99. 然后在spring配置文件中进行配置:   
  100. <bean id="sleepHelper" class="test.spring.aop.bean.SleepHelper">   
  101. </bean>   
  102.   
  103. OK!现在创建通知的工作就完成了.   
  104.   
  105. 第二步是进行配置,这是很令人蛋疼的操作,尤其是这么热的天,Spring又把东西的名字起的见鬼的长!它为啥不能像usr这种风格呢?   
  106.   
  107. 首先要做的是配置一个切点,据说切点的表示方式在Spring中有好几种,但是常用的只有两种:1.使用正则表达式 2.使用AspectJ表达式 AspectJ我不是很熟悉(我也是熟悉   
  108.   
  109. 党 or 精通党?),我还是习惯用正则表达式   
  110.   
  111. Spring使用org.springframework.aop.support.JdkRegexpMethodPointcut来定义正则表达式切点   
  112. <bean id="spleepPointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut">   
  113.   <property name="pattern" value=".*sleep"/>   
  114. </bean>   
  115.   
  116. pattern属性指定了正则表达式,它匹配所有的sleep方法   
  117.   
  118. 切点仅仅是定义了故事发生的地点,还有故事发生的时间以及最重要的故事的内容,就是通知了,我们需要把通知跟切点结合起来,我们要使用的通知者是:   
  119. org.springframework.aop.support.DefaultPointcutAdvisor   
  120.   
  121. <bean id="sleepHelperAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">   
  122.      <property name="advice" ref="sleepHelper"/>   
  123.      <property name="pointcut" ref="sleepPointcut"/>   
  124. </bean>   
  125.   
  126. 切入点和通知都配置完成,接下来该调用ProxyFactoryBean产生代理对象了   
  127.   
  128. <bean id="humanProxy" class="org.springframework.aop.framework.ProxyFactoryBean">   
  129.      <property name="target" ref="human"/>   
  130.      <property name="interceptorNames" value="sleepHelperAdvisor" />   
  131.      <property name="proxyInterfaces" value="test.spring.aop.bean.Sleepable" />   
  132. </bean>   
  133.   
  134. ProxyFactoryBean是一个代理,我们可以把它转换为proxyInterfaces中指定的实现该interface的代理对象:   
  135.   
  136. import org.springframework.aop.framework.ProxyFactoryBean;   
  137. import org.springframework.context.ApplicationContext;   
  138. import org.springframework.context.support.ClassPathXmlApplicationContext;   
  139.   
  140. import test.spring.aop.bean.Sleepable;   
  141.   
  142.   
  143. public class Test {   
  144.   
  145.     public static void main(String[] args){   
  146.         ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml");   
  147.         Sleepable sleeper = (Sleepable)appCtx.getBean("humanProxy");   
  148.         sleeper.sleep();   
  149.     }   
  150. }   
  151.   
  152. 程序运行产生结果:   
  153. 通常情况下睡觉之前要脱衣服!   
  154. 睡觉啦~梦中自有颜如玉!   
  155. 起床后要先穿衣服!   
  156.   
  157. OK!这是我们想要的结果,但是上面这个过程貌似有点复杂,尤其是配置切点跟通知,Spring提供了一种自动代理的功能,能让切点跟通知自动进行匹配,修改配置文件如下:   
  158.  <bean id="sleepHelper" class="test.spring.aop.bean.SleepHelper">   
  159.   </bean>   
  160.   <bean id="sleepAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">   
  161.     <property name="advice" ref="sleepHelper"/>   
  162.     <property name="pattern" value=".*sleep"/>   
  163.   </bean>   
  164.   <bean id="human" class="test.spring.aop.bean.Human">   
  165.   </bean>   
  166.   <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>   
  167.   
  168. 执行程序:   
  169. public class Test {   
  170.   
  171.     public static void main(String[] args){   
  172.         ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml");   
  173.         Sleepable sleeper = (Sleepable)appCtx.getBean("human");   
  174.         sleeper.sleep();   
  175.     }   
  176. }   
  177. 成功输出结果跟前面一样!   
  178. 只要我们声明了org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator(我勒个去的,名太长了)就能为方法匹配的bean自动创建代理!   
  179.   
  180. 但是这样还是要有很多工作要做,有更简单的方式吗?有!   
  181.   
  182. 一种方式是使用AspectJ提供的注解:   
  183.   
  184. package test.mine.spring.bean;   
  185.   
  186. import org.aspectj.lang.annotation.AfterReturning;   
  187. import org.aspectj.lang.annotation.Aspect;   
  188. import org.aspectj.lang.annotation.Before;   
  189. import org.aspectj.lang.annotation.Pointcut;   
  190. @Aspect  
  191. public class SleepHelper {   
  192.   
  193.     public SleepHelper(){   
  194.            
  195.     }   
  196.        
  197.     @Pointcut("execution(* *.sleep())")   
  198.     public void sleeppoint(){}   
  199.        
  200.     @Before("sleeppoint()")   
  201.     public void beforeSleep(){   
  202.         System.out.println("睡觉前要脱衣服!");   
  203.     }   
  204.        
  205.     @AfterReturning("sleeppoint()")   
  206.     public void afterSleep(){   
  207.         System.out.println("睡醒了要穿衣服!");   
  208.     }   
  209.        
  210. }   
  211.   
  212. @Aspect的注解来标识切面,注意不要把它漏了,否则Spring创建代理的时候会找不到它,@Pointcut注解指定了切点,@Before@AfterReturning指定了运行时的通知,注   
  213.   
  214. 意的是要在注解中传入切点的名称   
  215.   
  216. 然后我们在Spring配置文件上下点功夫,首先是增加AOP的XML命名空间和声明相关schema   
  217. 命名空间:   
  218. xmlns:aop="http://www.springframework.org/schema/aop"  
  219. schema声明:   
  220. http://www.springframework.org/schema/aop   
  221. http://www.springframework.org/schema/aop/spring-aop-2.0.xsd   
  222.   
  223. 然后加上这个标签:   
  224. <aop:aspectj-autoproxy/> 有了这个Spring就能够自动扫描被@Aspect标注的切面了   
  225.   
  226. 最后是运行,很简单方便了:   
  227. public class Test {   
  228.   
  229.     public static void main(String[] args){   
  230.         ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml");   
  231.         Sleepable human = (Sleepable)appCtx.getBean("human");   
  232.         human.sleep();   
  233.     }   
  234. }   
  235.   
  236. 下面我们来看最后一种常用的实现AOP的方式:使用Spring来定义纯粹的POJO切面   
  237.   
  238. 前面我们用到了<aop:aspectj-autoproxy/>标签,Spring在aop的命名空间里面还提供了其他的配置元素:   
  239. <aop:advisor> 定义一个AOP通知者   
  240. <aop:after> 后通知   
  241. <aop:after-returning> 返回后通知   
  242. <aop:after-throwing> 抛出后通知   
  243. <aop:around> 周围通知   
  244. <aop:aspect>定义一个切面   
  245. <aop:before>前通知   
  246. <aop:config>顶级配置元素,类似于<beans>这种东西   
  247. <aop:pointcut>定义一个切点   
  248.   
  249. 我们用AOP标签来实现睡觉这个过程:   
  250. 代码不变,只是修改配置文件,加入AOP配置即可:   
  251. <aop:config>   
  252.     <aop:aspect ref="sleepHelper">   
  253.     <aop:before method="beforeSleep" pointcut="execution(* *.sleep(..))"/>   
  254.     <aop:after method="afterSleep" pointcut="execution(* *.sleep(..))"/>   
  255.     </aop:aspect>   
  256. </aop:config>   
  257.   
  258. 完!   
  259.   
  260. OK~~基本上就这么多了吧,要想用好还得多折腾折腾,另外玩玩AspectJ~不就是个玩!