前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >动态代理和nanning AOP(1)

动态代理和nanning AOP(1)

作者头像
田春峰-JCJC错别字检测
发布2019-02-14 15:06:00
3550
发布2019-02-14 15:06:00
举报

动态代理和nanning AOP

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

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

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

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

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

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

动态代理的定义如下:

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/

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2004年04月28日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档