码迷,mamicode.com
首页 > 编程语言 > 详细

spring的aop的例子

时间:2015-01-15 10:35:56      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:

一个简单的Spring的AOP例子   

2009-06-23 11:33:29|  分类: Spring |  标签: |举报 |字号 订阅

 

 

 

 

 

 

  1. package aop;   
  2. /**    
  3.  * 目标对象的接口   
  4.  */    
  5. public interface Student {   
  6.     public void addStudent(String name);   
  7. }  
package aop;  /**     * 目标对象的接口    */   public interface Student {   public void addStudent(String name);  }    


 

 
  1. package aop;   
  2. /**    
  3.  * 目标对象   
  4.  */    
  5. public class StudentImpl implements Student {   
  6.   
  7.     public void addStudent(String name) {   
  8.         System.out.println(" 欢迎  " + name + "  你加入);   
  9.     }   
  10. }  
package Spring家庭! ");   }  }    


 

 
  1. package aop;   
  2.   
  3. import java.lang.reflect.Method;   
  4. import org.springframework.aop.MethodBeforeAdvice;   
  5.   
  6. /**  
  7.  * 前置通知  
  8.  */  
  9. public class BeforeAdvice implements MethodBeforeAdvice {   
  10.   
  11.     public void before(Method method, Object[] args, Object target)   
  12.             throws Throwable {   
  13.   
  14.         System.out.println(" 这是BeforeAdvice类的before方法. ");   
  15.   
  16.     }   
  17. }  
package aop.MethodBeforeAdvice;    /**   * 前置通知   */  public class BeforeAdvice implements MethodBeforeAdvice {     public void before(Method method, Object[] args, Object target)     throws Throwable {      System.out.println(" 这是BeforeAdvice类的before方法. ");     }  }  


 

 
  1. package aop;   
  2.   
  3. import java.lang.reflect.Method;   
  4. import org.springframework.aop.AfterReturningAdvice;   
  5.   
  6. /**  
  7.  * 后置通知  
  8.  */  
  9. public class AfterAdvice implements AfterReturningAdvice {   
  10.   
  11.     public void afterReturning(Object returnValue, Method method,   
  12.             Object[] args, Object target) throws Throwable {   
  13.         System.out.println("这是AfterAdvice类的afterReturning方法.");   
  14.     }   
  15.   
  16. }  
package aop.AfterReturningAdvice;    /**   * 后置通知   */  public class AfterAdvice implements AfterReturningAdvice {     public void afterReturning(Object returnValue, Method method,     Object[] args, Object target) throws Throwable {    System.out.println("这是AfterAdvice类的afterReturning方法.");   }    }  


 

 
  1. package aop;   
  2.   
  3. import org.aopalliance.intercept.MethodInterceptor;   
  4. import org.aopalliance.intercept.MethodInvocation;   
  5. /**  
  6.  * 环绕通知  
  7.  */  
  8. public class CompareInterceptor implements MethodInterceptor {   
  9.     public Object invoke(MethodInvocation invocation) throws Throwable {   
  10.         Object result = null;   
  11.         String stu_name = invocation.getArguments()[0].toString();   
  12.         if (stu_name.equals("dragon")) {   
  13.             // 如果学生是dragon时,执行目标方法,   
  14.             result = invocation.proceed();   
  15.         } else {   
  16.             System.out.println("此学生是" + stu_name + "而不是dragon,不批准其加入.");   
  17.         }   
  18.         return result;   
  19.     }   
  20. }  
package 



 

 
    1. version="1.0" encoding="UTF-8"?>  
    2. <!DOCTYPE beans PUBLIC "-//spring-beans.dtd">  
    3.   
    4.     
    5. id="beforeAdvice"
    6.  class="id
    7. ="afterAdvice" class="id="compareInterceptor" class="id
    ="studenttarget" class="id="student"  
  •         class="org.springframework.aop.framework.ProxyFactoryBean">  
  •         
    1. name="proxyInterfaces">  
    2.             
      1. aop.Student
      2.         
      3.         
      4. name="interceptorNames"
      5. >  
  •             
  •                 
  •                 
  •                 
  •             
  •         
  •         
  • name="target"
  • >  
  •             
  • bean="studenttarget"
  •  />  
  •         
  •     
  •   
  • <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//

     

     

     
    1. package
     aop;   
  •   
  • import org.springframework.context.ApplicationContext;   
  • import org.springframework.context.support.FileSystemXmlApplicationContext;   
  • /**  
  •  * 测试代码  
  •  */  
  • public class Test {   
  •   
  •     public static void main(String[] args) {   
  •          ApplicationContext ctx = new FileSystemXmlApplicationContext("/src/applicationContext.xml");   
  •          Student s = (Student)ctx.getBean("student");   
  •          s.addStudent("aaa");   
  •     }   
  •   
  • }  
  •  

     

    *****************************************************************************************************

    Spring AOP实例二

     

     

     

    最近在研究aop,看了点资料,总结如下:
    所谓AOP就是将分散在各个方法处的公共代码提取到一处,并通过类似拦截器的机制实现代码的动态整合。可以简单地想象成,在某个方法的调用前、执行中、调用后和抛出异常时,动态插入自己的代码。

    网上碰到个例子还不错,整理了一下:

    首先看一个简单的spring IOC例子:

    用户买书接口:

     
    1. package aop;   
    2. public interface BuyBook {     
    3.     public void buyBook(String customer,String book)throws NoBookException;   
    4. }  
    package aop;  public interface BuyBook {    public void buyBook(String customer,String book)throws NoBookException;  }



    用户买书的接口实现:

     
    1. package aop;   
    2. public class BuyBookImpl implements BuyBook{   
    3.     public void buyBook(String customer,String book) {         
    4.         System.out.println(customer+"你好!你成功购了一本"+book+"!");   
    5.     }   
    6. }  
    package aop;  public class BuyBookImpl implements BuyBook{   public void buyBook(String customer,String book) {      System.out.println(customer+"你好!你成功购了一本"+book+"!");   }  }



    测试用户买书类:

     
    1. package aop;   
    2. import org.springframework.context.ApplicationContext;   
    3. import org.springframework.context.support.FileSystemXmlApplicationContext;   
    4.   
    5. public class TestAop {   
    6.     public static void main(String args[]) throws Exception{           
    7.         ApplicationContext ctx = new FileSystemXmlApplicationContext("aop.xml");      
    8.         BuyBook b = (BuyBook)ctx.getBean("newBuyBook");   
    9.         b.buyBook("小东", "《楚留香》");   
    10.     }   
    11. }  
    package aop;  import org.springframework.context.ApplicationContext;  import org.springframework.context.support.FileSystemXmlApplicationContext;    public class TestAop {   public static void main(String args[]) throws Exception{            ApplicationContext ctx = new FileSystemXmlApplicationContext("aop.xml");             BuyBook b = (BuyBook)ctx.getBean("newBuyBook");          b.buyBook("小东", "《楚留香》");      }  }



    配置文件aop.xml

     
      1. version="1.0" encoding="UTF-8"?>  
      2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">  
      3.     
      4. id="newBuyBook"
      5.  class="aop.BuyBookImpl"/>    
    1. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="newBuyBook" class="aop.BuyBookImpl"/> </beans>



      此时运行程序仅出现:
      小东你好!你成功购了一本《楚留香》!

      ===================================================================================
      AOP ----切面编程
      所谓切面编程:在不改变原方法(令为methodA)的定义与使用、也不改变原程序的流程的情况下,变更该methodA的功能。在变更时,最激动人心的时能获得methodA的类的对象,meahtoidA的参数,也可获得mehodA执行的结果,还能得到调用meahtoidA的对象。
          简单理解:允许用户在指定地方,插入新的函数,
      包括:
      1 methodA运行前,执行用户指定的其它方法methodOther,然后返回
      2 methodA运行完毕,执行用户指的其它方法methodOther,然后返回
      3 在执行methodA的地方,变成执行在用户指定的其它方法methodOther,
      在methodOther方法中, methodA运不运行,何时运行,随用户自行安排,然后返回
      4  methodA执行出现异常时,执行用户指定的其它方法methodOther,然后返回。

      产生动机:
      在一个程序中,当我们要 使用一个方法(令为methodA);由于不同的用户对methodA的功能要 求不一样,因此在这个methodA的地方就出现了变化点。所以要在这个变化点上进行封装,留下一个可扩展的接口,便于日后修改维护。

      本质:
      1  Aop核心是一个适配器,把变动前的方法,与变动后的方法联接在一起。
      2  这个适配器实现的核心是动态代理 Proxy机制
      3  四个核心子接口:
      a  MethodBeforeAdvice ----methodA函数调用前执行用户定义的方法
      b  AfterReturningAdvice ----- methodA函数调后执行用户定义的方法
      c  MethodInterceptor -------彻底变更MethodA函数为用户定义的方法
      d  ThrowsAdvice------methodA函数调用出现异常执行用户定义的方法

      ===================================================================================
      下面加入aop的内容:
      一、在买书前加入新功能(欢迎光临!小东)

      增加类MyBeforeAdvice :

       
      1. package
       aop;   
    2. import org.springframework.aop.MethodBeforeAdvice;   
    3. import java.lang.reflect.Method;   
    4.   
    5. public class MyBeforeAdvice implements MethodBeforeAdvice{   
    6.     public void before(Method arg0, Object[] arg1, Object target) throws Throwable {   
    7.     String customer = (String)arg1[0];         
    8.         System.out.println("欢迎光临!"+customer+"!");      
    9.     }      
    10. }  

 

package aop;  import org.springframework.aop.MethodBeforeAdvice;  import java.lang.reflect.Method;    public class MyBeforeAdvice implements MethodBeforeAdvice{   public void before(Method arg0, Object[] arg1, Object target) throws Throwable {   String customer = (String)arg1[0];            System.out.println("欢迎光临!"+customer+"!");         }   }

 



修改配置文件aop.xml:

 

 
      1. version="1.0" encoding="UTF-8"?>  
      2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">  
      3.     
      4. id="buyBook"
      5.  class="aop.BuyBookImpl"/>    
  •     
    1. id="myBeforeAdvice" class="aop.MyBeforeAdvice"/>  
    2.     
      1. id="newBuyBook" class="org.springframework.aop.framework.ProxyFactoryBean">  
      2.         
        1. name="proxyInterfaces" value="aop.BuyBook"/>    
        2.         
          1. name="interceptorNames">  
          2.             
          3.                   
        3.             
        4.         
      3.         
      4. name="target"
      5.  ref="buyBook"/>  
  •     
  • <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="buyBook" class="aop.BuyBookImpl"/> <bean id="myBeforeAdvice" class="aop.MyBeforeAdvice"/> <bean id="newBuyBook" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces" value="aop.BuyBook"/> <property name="interceptorNames"> <list> <value>myBeforeAdvice</value> </list> </property> <property name="target" ref="buyBook"/> </bean> </beans>



    运行后输出结果:
    欢迎光临!
    小东你好!你成功购了一本《楚留香》!


    二、在买书后加入新功能(Good Bye!小东)

    增加MyAfterAdvice类:

     
    1. package
     aop;   
  • import java.lang.reflect.Method;   
  • import org.springframework.aop.AfterReturningAdvice;   
  • public class MyAfterAdvice implements AfterReturningAdvice{    
  •     public void afterReturning(Object o1, Method m, Object[] objects, Object o2){      
  •         System.out.println("Good Bye!" + objects[0]);          
  •     }   
  • }  

 

package aop;  import java.lang.reflect.Method;  import org.springframework.aop.AfterReturningAdvice;  public class MyAfterAdvice implements AfterReturningAdvice{    public void afterReturning(Object o1, Method m, Object[] objects, Object o2){     System.out.println("Good Bye!" + objects[0]);     }  }

 



修改配置文件aop.xml:

 

 
      1. version="1.0" encoding="UTF-8"?>  
      2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">  
      3.     
      4. id="buyBook"
      5.  class="aop.BuyBookImpl"/>    
  •     
    1. id="myBeforeAdvice" class="aop.MyBeforeAdvice"/>  
    2.     
      1. id="myAfterAdvice" class="aop.MyAfterAdvice"/>  
      2.     
        1. id="newBuyBook" class="org.springframework.aop.framework.ProxyFactoryBean">  
        2.         
          1. name="proxyInterfaces" value="aop.BuyBook"/>    
          2.         
            1. name="interceptorNames">  
            2.             
            3.                   
          3.                   
        3.             
        4.         
      3.         
      4. name="target"
      5.  ref="buyBook"/>  
  •     
  • <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="buyBook" class="aop.BuyBookImpl"/> <bean id="myBeforeAdvice" class="aop.MyBeforeAdvice"/> <bean id="myAfterAdvice" class="aop.MyAfterAdvice"/> <bean id="newBuyBook" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces" value="aop.BuyBook"/> <property name="interceptorNames"> <list> <value>myBeforeAdvice</value> <value>myAfterAdvice</value> </list> </property> <property name="target" ref="buyBook"/> </bean> </beans>




    运行后输出结果:
    欢迎光临!
    小东你好!你成功购了一本《楚留香》!
    Good Bye!小东

    三、修改原来方法的内容,比如加入相关业务判断,一个人只能买一本书:
    修改用户买书类:

    package
     aop;   
  • import org.springframework.context.ApplicationContext;   
  • import org.springframework.context.support.FileSystemXmlApplicationContext;   
  •   
  • public class TestAop {   
  •     public static void main(String args[]) throws Exception{           
  •         ApplicationContext ctx = new FileSystemXmlApplicationContext("aop.xml");      
  •         BuyBook b = (BuyBook)ctx.getBean("newBuyBook");   
  •         b.buyBook("小东", "《楚留香》");   
  •         b.buyBook("小东", "《楚留香2》");   
  •     }   
  • }  

 

package aop;  import org.springframework.context.ApplicationContext;  import org.springframework.context.support.FileSystemXmlApplicationContext;    public class TestAop {   public static void main(String args[]) throws Exception{            ApplicationContext ctx = new FileSystemXmlApplicationContext("aop.xml");             BuyBook b = (BuyBook)ctx.getBean("newBuyBook");          b.buyBook("小东", "《楚留香》");          b.buyBook("小东", "《楚留香2》");      }  }

 



增加拦截器类MyMethodInterceptor:

 

package aop;   
  1. import java.util.HashSet;   
  2. import java.util.Set;   
  3. import org.aopalliance.intercept.MethodInterceptor;   
  4. import org.aopalliance.intercept.MethodInvocation;   
  5. public class MyMethodInterceptor implements MethodInterceptor{   
  6.     private Set customers = new HashSet();     
  7.     @Override  
  8.     public Object invoke(MethodInvocation invocation) throws Throwable {   
  9.         String customer = (String)invocation.getArguments()[0];   
  10.         Object result = null;   
  11.         if(customers.contains(customer)){   
  12.              System.out.println("注意,一名顾客只能买一本打折书!");   
  13.         } else{   
  14.              result = invocation.proceed();   
  15.         }   
  16.         customers.add(customer);   
  17.         return result;   
  18.     }   
  19. }  

 

package aop;  import java.util.HashSet;  import java.util.Set;  import org.aopalliance.intercept.MethodInterceptor;  import org.aopalliance.intercept.MethodInvocation;  public class MyMethodInterceptor implements MethodInterceptor{   private Set customers = new HashSet();    @Override   public Object invoke(MethodInvocation invocation) throws Throwable {    String customer = (String)invocation.getArguments()[0];       Object result = null;       if(customers.contains(customer)){            System.out.println("注意,一名顾客只能买一本打折书!");       } else{            result = invocation.proceed();       }       customers.add(customer);       return result;   }  }

 




修改配置文件aop.xml:

 

 
      1. version="1.0" encoding="UTF-8"?>  
      2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">  
      3.     
      4. id="buyBook"
      5.  class="aop.BuyBookImpl"/>    
  •     
    1. id="myMethodInterceptor" class="aop.MyMethodInterceptor"/>  
    2.   
    3.     
      1. id="newBuyBook" class="org.springframework.aop.framework.ProxyFactoryBean">  
      2.         
        1. name="proxyInterfaces" value="aop.BuyBook"/>    
        2.         
          1. name="interceptorNames">  
          2.             
          3.                   
        3.             
        4.         
      3.         
      4. name="target"
      5.  ref="buyBook"/>  
  •     
  • <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="buyBook" class="aop.BuyBookImpl"/> <bean id="myMethodInterceptor" class="aop.MyMethodInterceptor"/> <bean id="newBuyBook" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces" value="aop.BuyBook"/> <property name="interceptorNames"> <list> <value>myMethodInterceptor</value> </list> </property> <property name="target" ref="buyBook"/> </bean> </beans>



    运行结果:
    小东你好!你成功购了一本《楚留香》!
    注意,一名顾客只能买一本打折书!

 

spring的aop的例子

标签:

原文地址:http://www.cnblogs.com/hanxue53/p/4225463.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!