一个简单的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. public void addStudent(String name) {
  7. System.out.println(" 欢迎  " + name + "  你加入);
  8. }
  9. }
package Spring家庭! ");   }  }    
 
  1. package aop;
  2. import java.lang.reflect.Method;
  3. import org.springframework.aop.MethodBeforeAdvice;
  4. /**
  5. * 前置通知
  6. */
  7. public class BeforeAdvice implements MethodBeforeAdvice {
  8. public void before(Method method, Object[] args, Object target)
  9. throws Throwable {
  10. System.out.println(" 这是BeforeAdvice类的before方法. ");
  11. }
  12. }
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. import java.lang.reflect.Method;
  3. import org.springframework.aop.AfterReturningAdvice;
  4. /**
  5. * 后置通知
  6. */
  7. public class AfterAdvice implements AfterReturningAdvice {
  8. public void afterReturning(Object returnValue, Method method,
  9. Object[] args, Object target) throws Throwable {
  10. System.out.println("这是AfterAdvice类的afterReturning方法.");
  11. }
  12. }
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. import org.aopalliance.intercept.MethodInterceptor;
  3. import org.aopalliance.intercept.MethodInvocation;
  4. /**
  5. * 环绕通知
  6. */
  7. public class CompareInterceptor implements MethodInterceptor {
  8. public Object invoke(MethodInvocation invocation) throws Throwable {
  9. Object result = null;
  10. String stu_name = invocation.getArguments()[0].toString();
  11. if (stu_name.equals("dragon")) {
  12. // 如果学生是dragon时,执行目标方法,
  13. result = invocation.proceed();
  14. } else {
  15. System.out.println("此学生是" + stu_name + "而不是dragon,不批准其加入.");
  16. }
  17. return result;
  18. }
  19. }
package 
 
    1. version="1.0" encoding="UTF-8"?>
    2. <!DOCTYPE beans PUBLIC "-//spring-beans.dtd">
    3. id="beforeAdvice"
    4.  class="id
    5. ="afterAdvice" class="id="compareInterceptor" class="id

    ="studenttarget" class="id="student"

  • class="org.springframework.aop.framework.ProxyFactoryBean">
    1. name="proxyInterfaces">
      1. aop.Student
      2. name="interceptorNames"
      3. >  
  • 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. public class TestAop {
    5. public static void main(String args[]) throws Exception{
    6. ApplicationContext ctx = new FileSystemXmlApplicationContext("aop.xml");
    7. BuyBook b = (BuyBook)ctx.getBean("newBuyBook");
    8. b.buyBook("小东", "《楚留香》");
    9. }
    10. }
    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. id="newBuyBook"
      4.  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. public class MyBeforeAdvice implements MethodBeforeAdvice{
    5. public void before(Method arg0, Object[] arg1, Object target) throws Throwable {
    6. String customer = (String)arg1[0];
    7. System.out.println("欢迎光临!"+customer+"!");
    8. }
    9. }
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. id="buyBook"
      4.  class="aop.BuyBookImpl"/>    
    1. id="myBeforeAdvice" class="aop.MyBeforeAdvice"/>
      1. id="newBuyBook" class="org.springframework.aop.framework.ProxyFactoryBean">
        1. name="proxyInterfaces" value="aop.BuyBook"/>
          1. name="interceptorNames">
      2. name="target"
      3.  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. id="buyBook"
      4.  class="aop.BuyBookImpl"/>    
    1. id="myBeforeAdvice" class="aop.MyBeforeAdvice"/>
      1. id="myAfterAdvice" class="aop.MyAfterAdvice"/>
        1. id="newBuyBook" class="org.springframework.aop.framework.ProxyFactoryBean">
          1. name="proxyInterfaces" value="aop.BuyBook"/>
            1. name="interceptorNames">
      2. name="target"
      3.  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. id="buyBook"
      4.  class="aop.BuyBookImpl"/>    
    1. id="myMethodInterceptor" class="aop.MyMethodInterceptor"/>
      1. id="newBuyBook" class="org.springframework.aop.framework.ProxyFactoryBean">
        1. name="proxyInterfaces" value="aop.BuyBook"/>
          1. name="interceptorNames">
      2. name="target"
      3.  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的例子的更多相关文章

  1. Spring AOP 学习例子

    http://outofmemory.cn/code-snippet/3762/Spring-AOP-learn-example     工作忙,时间紧,不过事情再多,学习是必须的.记得以前的部门老大 ...

  2. Spring基于AOP的事务管理

                                  Spring基于AOP的事务管理 事务 事务是一系列动作,这一系列动作综合在一起组成一个完整的工作单元,如果有任何一个动作执行失败,那么事务 ...

  3. Spring实现AOP的4种方式

    了解AOP的相关术语:1.通知(Advice):通知定义了切面是什么以及何时使用.描述了切面要完成的工作和何时需要执行这个工作.2.连接点(Joinpoint):程序能够应用通知的一个“时机”,这些“ ...

  4. Spring的AOP与代理

    spring 支持两种注入方式: setter/constructor 支持多种配置方式: xml/java5注解/java类配置 支持两种事务管理: 声明性/编程性 实际上上述方式只有一个就能保证系 ...

  5. Spring实现AOP的4种方式(转)

    转自:http://blog.csdn.net/udbnny/article/details/5870076 Spring实现AOP的4种方式 先了解AOP的相关术语:1.通知(Advice):通知定 ...

  6. Spring学习笔记(二)Spring基础AOP、IOC

    Spring AOP 1. 代理模式 1.1. 静态代理 程序中经常需要为某些动作或事件作下记录,以便在事后检测或作为排错的依据,先看一个简单的例子: import java.util.logging ...

  7. Spring中AOP简介与切面编程的使用

    Spring中AOP简介与使用 什么是AOP? Aspect Oriented Programming(AOP),多译作 "面向切面编程",也就是说,对一段程序,从侧面插入,进行操 ...

  8. Spring之AOP二

    在Spring之AOP一中使用动态代理将日志打印功能注入到目标对象中,其实这就是AOP实现的原理,不过上面只是Java的实现方式.AOP不管什么语言它的几个主要概念还是有必要了解一下的. 一.AOP概 ...

  9. Spring【AOP模块】就是这么简单

    前言 到目前为止,已经简单学习了Spring的Core模块.....于是我们就开启了Spring的AOP模块了...在讲解AOP模块之前,首先我们来讲解一下cglib代理.以及怎么手动实现AOP编程 ...

随机推荐

  1. Microsoft Office Access数据库或项目包含一个对文件“dao360.dll”版本5.0.的丢失的或损坏的引用。

    今天使用 office 2007 access 打开 2003 的数据库中的表时候,提示这个错误.经过搜索,发现是没有 dao360.dll 的问题. 在 https://cn.dll-files.c ...

  2. 1.正则re

    正则 :规则表达式 一般在匹配非结构化的数据时用的比较多,结构化的数据一般用xpath,bs4.但具体使用起来都是视情况而定,相对而言.正则规则平时涉及最多也就是匹配邮箱,电话,及特殊字符串.规则相对 ...

  3. workerman-todpole 执行流程(1)

    该系列文章主要是彻底扒一下 workerman todpole 游戏的实现原理. 提前打个预防针: 由于 Worker 类的静态属性和子类对象的混用(当前类的静态属性存放当前类对象,静态方法循环静态属 ...

  4. python 求3到8位数的水仙花数Pycharm实现

    #-*- coding: utf-8-*-import timeimport math#获取3位数的水仙花数start1 = time.time()start = time.time() number ...

  5. DirectShow设置采集帧率码率YUV<转>

    // 设置参数,p1=宽,p2=高,p3=帧率 AM_MEDIA_TYPE *p = NULL; IAMStreamConfig *pSC = NULL; pCGB2->FindInterfac ...

  6. Leetcode 题解 First Missing Positive

    Given an unsorted integer array, find the first missing positive integer. For example,Given [1,2,0]  ...

  7. 容器viewController添加或者删除子viewController

    假设有一个viewControllerA,我们想在viewControllerA中添加viewControllerB,需要执行以下方法: [viewControllerA addChildViewCo ...

  8. js 提示框的实现---组件开发之(一)

    自己做了一个简单的提示框,供自己使用,也可以供他人参考,看懂此文,是理解组件开发的入门 思路比较简单: 1.常规写法: 1.1. 创建一个构造函数 1.2. 给构造函数的原型对象添加show 和hid ...

  9. 把网卡中断绑定到CPU,最大化网卡的吞吐量(转)

    先来看一下问题, 我们通过 ifconfig 查看接口的名称 为 p15p1, 一般机器为 eth0 再通过命令 ➜ ~ cat /proc/interrupts | head -n 1 && ...

  10. 腾讯助理PHP开发工程师外包岗面经

    校招错过腾讯了,在社招上看到腾讯有招外包岗,要求比正式岗低,于是抱着试一试的心态投了简历,没一会就收到了笔试题,还算简单. 第二天收到面试官的面试邀请,然后去面试了…… 腾讯里面真是漂亮,光是看装潢就 ...