手机版
你好,游客 登录 注册
背景:
阅读新闻

使用Spring进行切面(AOP)编程

[日期:2012-01-11] 来源:Linux社区  作者:wgw [字体:大 中 小]

4.         编写切面类AspectBean,代码如下

[Java]
  1. package com.trs.components.aop;  
  2. import org.aspectj.lang.JoinPoint;  
  3. import org.aspectj.lang.ProceedingJoinPoint;  
  4. import org.aspectj.lang.annotation.After;  
  5. import org.aspectj.lang.annotation.AfterThrowing;  
  6. import org.aspectj.lang.annotation.Around;  
  7. import org.aspectj.lang.annotation.Aspect;  
  8. import org.aspectj.lang.annotation.Before;  
  9. /** 
  10.  * 拦截StudentMgr的切面 
  11.  *  
  12.  *  
  13.  */  
  14. @Aspect  
  15. // 声明一个切面   
  16. public class AspectBean {  
  17.     @Before("execution (* com.trs.components.mgr.StudentMgr.update*(..))")  
  18.   
  19.     // 声明前置通知,拦截StudentMgr的所有以update开头的方法   
  20.   
  21.     public void validateUser(JoinPoint pjp) throws Throwable {  
  22.   
  23.         System.out.println("执行用户验证!");  
  24.   
  25.     }  
  26.   
  27.     @Before("execution (* com.trs.components.mgr.StudentMgr.update*(..))")  
  28.   
  29.     // 声明前置通知,拦截StudentMgr的所有以update开头的方法   
  30.   
  31.     public void beginTransaction(JoinPoint _jp) throws Throwable {  
  32.   
  33.         // 如果需要对连接点传入的参数进行处理,可以通过代码获取:_jp.getArgs();   
  34.   
  35.         System.out.println("开始事务");  
  36.   
  37.     }  
  38.   
  39.     @After("execution (* com.trs.components.mgr.StudentMgr.update*(..))")  
  40.   
  41.     // 声明最终通知,拦截StudentMgr的所有以update开头的方法   
  42.   
  43.     public void endTransaction() throws Throwable {  
  44.   
  45.         System.out.println("结束事务");  
  46.   
  47.     }  
  48.   
  49.     @After("execution (* com.trs.components.mgr.StudentMgr.update*(..))")  
  50.   
  51.     // 声明最终通知,拦截StudentMgr的所有以update开头的方法   
  52.   
  53.     public void writeLogInfo() {  
  54.   
  55.         System.out.println("记录日志信息");  
  56.   
  57.     }  
  58.   
  59.     @AfterThrowing(pointcut = "execution (* com.trs.components.mgr.StudentMgr.update*(..))", throwing = "ex")  
  60.   
  61.     // 声明异常,StudentMgr类的update方法出现异常时执行   
  62.   
  63.     public void printException(Exception ex) {  
  64.   
  65.         System.out.println("执行update方法时发生错误" + ex.getMessage());  
  66.   
  67.     }  
  68.   
  69.     @Around("execution (* com.trs.components.mgr.StudentMgr.update*(..))")  
  70.   
  71.     // 声明环绕通知,拦截StudentMgr的所有以update开头的方法   
  72.   
  73.     public Object doSurround(ProceedingJoinPoint _pjp)throws Throwable {  
  74.   
  75.         // 如果需要对连接点传入的参数进行处理,可以通过代码获取:pjp.getArgs();   
  76.   
  77.         Object result;  
  78.   
  79.         if (true) {  
  80.   
  81.             // 这里可以根据条件决定是否进入这个if   
  82.   
  83.             System.out.println("进入环绕通知...");  
  84.   
  85.             result = _pjp.proceed();// 使用环绕通知时,这个方法必须要执行,否则被拦截的方法就不会再执行了   
  86.   
  87.             System.out.println("退出环绕通知...");  
  88.   
  89.         }  
  90.   
  91.         // 返回执行后的返回值   
  92.   
  93.         return result;  
  94.   
  95.     }  
  96.   
  97. }  

说明:

[1]       @Before("execution (* com.trs.components.mgr.StudentMgr.update*(..))") 第一个*号表示匹配方法的返回值可以使任何类型;第二个*号表示所有以update开头的方法都会被拦截;(..)表示这些方法输入的参数可以0或者多个。

[2]       @AfterThrowing中的 throwing = "ex",表示方法出错的时候会返回一个名称为ex的异常,在切入点中通过参数ex即可获取到出错的异常对象。

[3]       环绕方法doSurround的写法需要注意

l  环绕方法中的第一个参数类型必须是ProceedingJoinPoint类型(环绕的方法名可以随便起名)。

l  环绕方法抛的异常需要时Throwable类型

l  环绕方法中需要执行_pjp.proceed()方法,否则被拦截的方法不会执行

l  在_pjp.proceed()方法前后各加一个时间点,可以用来测试被拦截的方法的执行时间

5.         切面类的一些bean配置

在Spring的配置文件中加入如下代码,配置相关的bean类。

<?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:context="http://www.springframework.org/schema/context"

    xmlns:aop="http://www.springframework.org/schema/aop"

    xsi:schemaLocation="http://www.springframework.org/schema/beans            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

           http://www.springframework.org/schema/context           http://www.springframework.org/schema/context/spring-context-2.5.xsd

           http://www.springframework.org/schema/aop           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd ">

 

         <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />

         <bean id="aspectBean" class="com.trs.components.aop.AspectBean"></bean>

         <bean id="IStudentMgr" class="com.trs.components.mgr.StudentMgr"></bean>

</beans>

6.         编写测试用例

利用Junit编写测试StudentMgr.update方法的测试用例,测试用例相关方法代码如下:

@Test

    public void testUpdate() throws Exception {

        // 使用ApplicationContext来初始化系统

        ApplicationContext context = new ClassPathXmlApplicationContext(

                "applicationContext.xml");

         IStudentMgr studentMgr = (IStudentMgr) context.getBean("IStudentMgr");

        // studentMgr.saveOne("wuguowei");

        System.out.println("-----------");

        studentMgr.update("wuguowei");

     }

7.         执行测试用例,查看打印结果

开始事务

执行用户验证!

进入环绕通知...

更新了学生对象..

结束事务

记录日志信息

退出环绕通知...

8.         实例对应的XML配置的AOP编程

上面我们给出的是注解风格的AOP编程,上面实例的编程同样可以采用XML配置方式的AOP编程,我们只需要在Spring的配置文件中添加如下代码即可(AOP的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:context="http://www.springframework.org/schema/context"

    xmlns:aop="http://www.springframework.org/schema/aop"

    xsi:schemaLocation="http://www.springframework.org/schema/beans            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

           http://www.springframework.org/schema/context           http://www.springframework.org/schema/context/spring-context-2.5.xsd

           http://www.springframework.org/schema/aop           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd ">

         <aop:config>  

                   <aop:aspect id="asp_bean_id" ref="aspectBean">  

                            <aop:pointcut id="mypointcut" expression="execution (* com.trs.components.mgr.StudentMgr.update*(..))"/>  

                            <aop:before pointcut-ref="mypointcut" method="validateUser"/> 

                            <aop:before pointcut-ref="mypointcut" method="beginTransaction"/>  

                            <aop:after pointcut-ref="mypointcut" method="endTransaction"/>  

                            <aop:after pointcut-ref="mypointcut" method="writeLogInfo"/> 

                            <aop:after-throwing pointcut-ref="mypointcut" method="printException"/>

                            <aop:around pointcut-ref="mypointcut" method="doSurround"/>  

                   </aop:aspect>  

         </aop:config>  

 

         <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />

         <bean id="AnotherAspect" class="com.trs.components.aop.AnotherAspect"></bean>

         <bean id="aspectBean" class="com.trs.components.aop.AspectBean"></bean>

         <bean id="IStudentMgr" class="com.trs.components.mgr.StudentMgr"></bean>

</beans>

 

linux
相关资讯       Spring 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款