动态代理和nanning AOP(1)

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

动态代理和nanning AOP

关键字: AOP Nanning Dynamic proxy AOP 动态代理

大家知道AOP编程目前有三种途径:

1、 类似AspectJ,使用特定的语法将代码插入到相应代码中的过程,一般是编译完成在编译时修改java类代码实现,interception and introduct 等,;

2、 类似 JbossAOP ,在类加载时利用反射机制实现AOP的功能;

3、 类似nanning(南宁)使用java 动态代理。

动态代理的定义如下:

http://java.sun.com/j2se/1.3/docs/guide/reflection/proxy.html

A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface.

也就是说要用动态代理,那么一个类的行为需要实现统一的一个或多个接口才能实现,当这个类实例的方法被调用的时候,可以对之进行一些拦截处理。

举例如下:

接口类:

public interface Foo {

Object bar(Object obj) throws BazException;

}

实现类:

public class FooImple implements Foo {

public Object bar(Object obj) throws BazException {

return obj;

// ...

}

}

动态代理类的实现:

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

public class DebugProxy implements java.lang.reflect.InvocationHandler {

private Object obj;

public static Object newInstance(Object obj) {

return java.lang.reflect.Proxy.newProxyInstance(obj.getClass()

.getClassLoader(), obj.getClass().getInterfaces(),

new DebugProxy(obj));

}

private DebugProxy(Object obj) {

this.obj = obj;

}

public Object invoke(Object proxy, Method m, Object[] args)

throws Throwable {

Object result;

try {

System.out.println("before method " + m.getName());

result = m.invoke(obj, args);

} catch (InvocationTargetException e) {

throw e.getTargetException();

} catch (Exception e) {

throw new RuntimeException("unexpected invocation exception: "

+ e.getMessage());

} finally {

System.out.println("after method " + m.getName());

}

return result;

}

}

测试类:

public class test {

public static void main(String[] args) throws BazException {

Foo foo = (Foo) DebugProxy.newInstance(new FooImple());

foo.bar(null);

}

}

运行效果如下:

before method bar

after method bar

可以看到:执行 foo.bar(null); 的时候,动态代理实现了对这个方法调用前和调用后的拦截。

方法拦截 interception 是AOP的特点之一。

基于动态代理的AOP实现一般是轻量级AOP Framewrok的首选,比如:nanning 和 springframework。

下文我们介绍nanning aop 的实现。

参考资料

http://www.csdn.net/develop/article/24/24445.shtm

作者:田春峰

专栏地址:http://www.csdn.net/develop/author/NetAuthor/accesine960/

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航