SpringFramework中的AOP简单使用
SpringFramework中的AOP简单使用
AOP作为Spring这个轻量级的容器中很重要的一部分,得到越来越多的关注,Spring的Transaction就是用AOP来管理的,今天就通过简单的例子来看看Spring中的AOP的基本使用方法。
  首先确定将要Proxy的目标,在Spring中默认采用JDK中的dynamic proxy,它只能够实现接口的代理,如果想对类进行代理的话,需要采用CGLIB的proxy。显然,选择“编程到接口”是更明智的做法,下面是将要代理的接口:
  public interface FooInterface {
    public void printFoo();
    public void dummyFoo();
  }
 
  以及其一个简单的实现:
 
  public class FooImpl implements FooInterface {
    public void printFoo() {
      System.out.println("In FooImpl.printFoo");
    }
    public void dummyFoo() {
      System.out.println("In FooImpl.dummyFoo");
    }
  }
 
  接下来创建一个Advice,在Spring中支持Around,Before,After returning和Throws四种Advice,这里就以简单的Before Advice举例:
 
  public class PrintBeforeAdvice implements MethodBeforeAdvice {
    public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
      System.out.println("In PrintBeforeAdvice");
    }
  }
 
  有了自己的business interface和advice,剩下的就是如何去装配它们了,首先利用ProxyFactory以编程方式实现,如下:
 
  public class AopTestMain {
    public static void main(String[] args) {
      FooImpl fooImpl = new FooImpl();
      PrintBeforeAdvice myAdvice = new PrintBeforeAdvice();
     
      ProxyFactory factory = new ProxyFactory(fooImpl);
      factory.addBeforeAdvice(myAdvice);
      FooInterface myInterface = (FooInterface)factory.getProxy();
      myInterface.printFoo();
      myInterface.dummyFoo();
    }
  }
 
  现在执行程序,神奇的结果就出现了:
 
  In PrintBeforeAdvice
  In FooImpl.printFoo
  In PrintBeforeAdvice
  In FooImpl.dummyFoo
 
  虽然这样能体会到Spring中AOP的用法,但这决不是值得推荐的方法,既然使用了Spring,在ApplicationContext中装配所需要 的bean才是最佳策略,实现上面的功能只需要写个简单的applicationContext就可以了,如下:
 
  <?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
  <beans>
    <description>The aop application context</description>
	
相关新闻>>
- 发表评论
 - 
				
 
- 最新评论 进入详细评论页>>
 






