Java编程中使用动态代理实现AOP功能

开发 后端
本文详细介绍了Java编程中使用动态代理实现AOP功能,AOP是OOP的延续,是Aspect Oriented Programming的缩写,意思是面向切面编程。

一、Java编程使用的背景

也不能算是使用的背景,最多只能算是一个在什么条件下面我想到了使用动态代理实现AOP的拦截功能):因为在项目中程序的结构是使用SOAP调用JNI,因此在SOAP服务端里面没有任何实现代码,仅仅是new一个JNI的对象,然后调用JNI对应的方法。但是在调用JNI方法之前需要对传进JNI的JavaBean进行初始化,而且还需要记录日志。而SOAP服务端的代码是通过ant自动生成的,需要对他进行手工的修改,在修改过程中发现每一个方法里面都是相同的:记录进入方法的日志、初始化JavaBean和记录退出方法的日志,这写东西都是通过拷贝粘贴来完成的,想到如果以后再加一个什么功能的时候又得每一个方法进行拷贝粘贴,而且方法的数量还不少,所以觉得这样来实现是不科学的。示例代码如下:  

  1. public class SOAP{   
  2.  
  3. private JniInterface jni = null;   
  4.  
  5. private Log log = 。。。;   
  6.  
  7. public SOAP(){   
  8.  
  9. jni=new JniClass();   
  10.  
  11. }   
  12.  
  13.  
  14. /**方法A**/   
  15.  
  16. public JavaBeanA aMethod(JavaBeanA javaBeanA){   
  17.  
  18. log.debug("进入A方法");   
  19.  
  20. //初始化JavaBean   
  21.  
  22. Init(javaBeanA);   
  23.  
  24. //调用JNI对应的方法   
  25.  
  26. JavaBeanA result = jni.aMethod(javaBeanA);   
  27.  
  28. log.debug("退出A方法");   
  29.  
  30. return result;   
  31.  
  32. }   
  33.  
  34. ……………………………………   
  35.  
  36. ……………………………………   
  37.  
  38. 等等,很多这样的方法   
  39.  
  40. ……………………………………   
  41.  
  42. ……………………………………   
  43.  
  44. }   
  45.  

从示例代码里面可以看出,除了调用JNI对应的方法不同之外,其他的都是相同的代码,把所有的东西进行拷贝复制是不合理的。每当对SOAP进行修改,就必须将所有的方法重新拷贝粘贴。为了省去拷贝粘贴这一工序,所以使用动态代理实现AOP拦截共能。

二、实现AOP拦截

1.定义Interceptor接口

  1. public interface Interceptor {   
  2.  
  3. //在调用之前调用该方法   
  4.  
  5. public void before(InvokeJniInfo invInfo);   
  6.  
  7. //在调用之后调用该方法   
  8.  
  9. public void after(InvokeJniInfo invInfo);   
  10.  
  11. //出现异常之后调用该方法   
  12.  
  13. public void exceptionThrow(InvokeJniInfo invInfo);   
  14.  
  15. }   

2. 定义 InvokeJniInfo 类

在Interceptor接口中的InvokeJniInfo类,该类的定义如下:

  1. public class InvokeJniInfo {   
  2.  
  3. //被代理的对象   
  4.  
  5. Object proxy;   
  6.  
  7. //被调用的方法   
  8.  
  9. Method method;   
  10.  
  11. //被调用方法的参数列表   
  12.  
  13. Object[] args;   
  14.  
  15. //调用之后的结果   
  16.  
  17. Object result;   
  18.  
  19. //抛出的异常   
  20.  
  21. Throwable exception;   
  22.  
  23.  
  24. public InvokeJniInfo(Object proxy,   
  25.  
  26. Method method,   
  27.  
  28. Object[] args,   
  29.  
  30. Object result,   
  31.  
  32. Throwable exception){   
  33.  
  34. this.proxy = proxy;   
  35.  
  36. this.method = method;   
  37.  
  38. this.args = args;   
  39.  
  40. this.result = result;   
  41.  
  42. this.exception = exception;   
  43.  
  44. }   
  45.  
  46. …………………………………………………………   
  47.  
  48. …………………………………………………………   

所有成员的get/set方法

…………………………………………………………

…………………………………………………………

}

从该类的成员变量可以知道,这个类使用来将调用函数的基本信息如代理的对象,调用的方法,调用方法的参数等信息传递给Interceptor,使得在Interceptor 之中可以通过使用该对象作出相应的拦截。


3.实现一个抽象的拦截器AbstractInterceptor

该拦截器实现了Interceptor接口,它里面的方法全都是空的,其目的是当某些拦截器只是需要实现三个方法中的一个方法或者两个方法的时候,就可以继承该抽象类,覆盖需要的实现的方法就可以了。

4.实现日志记录拦截器LogInterceptor

该拦截器主要是实现在调用之前记录日志,调用之后记录日志和出现异常的时候记录日志。其代码如下:

  1. public class LogInterceptor implements Interceptor {

  2. private Log log = LogFactory.getLog(“初始化Log” );

  3. public void before(InvokeJniInfo invInfo) {

  4. //调用InvokeJniInfo对象的Method的getName方法获取方法名

  5. log.debug("Enter the" + invInfo.getMethod().getName());

  6. }

  7. public void after(InvokeJniInfo invInfo) {

  8. //调用InvokeJniInfo对象的Method的getName方法获取方法名

  9. log.debug("Exit the" + invInfo.getMethod().getName());

  10. }

  11. public void exceptionThrow(InvokeJniInfo invInfo) {

  12. //调用InvokeJniInfo对象的Method的getName方法获取方法名

  13. log.error("Call the" + invInfo.getMethod().getName() + " has error!");

  14. //调用InvokeJniInfo对象的Exception的getStackTrace方法获取具体异常并记录

  15. log.error(invInfo.getException().getStackTrace());   
  16. }   
  17.  
  18. }   

5.实现初始化JavaBean拦截器InitParamsInterceptor

该类继承AbstractInterceptor,只需覆盖before方法即可。其代码如下:

  1. public class InitParamsInterceptor extends AbstractInterceptor {   
  2.  
  3.  
  4. public void before(InvokeJniInfo invInfo) {   
  5.  
  6. if(invInfo.getArgs().length>0){   

//初始化***个参数

  1. InitContainsObjectNullUtil.initContainsOutParameter(invInfo.getArgs()[0]);   
  2. }   
  3.  
  4. }   
  5.  
  6.  
  7. }   

6.实现动态代理处理器InterceptorHandler

该类实现了java.lang.reflect.InvocationHandler接口。

  1. public class InterceptorHandler implements InvocationHandler {

  2. private static Log log = LogFactory.getLog(InterceptorHandler.class);

  3. //拦截器列表

  4. private List interceptors = null;

  5. //存放原始对象

  6. private Object orginalObject;

  7. //使用Proxy返回一个对象。注意这里传进去的对象的对象必须实现一个接口

  8. public Object bind(Object obj) {   
  9.  
  10. this.orginalObject = obj;   
  11.  
  12. return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj   
  13.  
  14. .getClass().getInterfaces(), this);   
  15.  
  16. }   
  17.  
  18.  
  19.  
  20. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {   
  21.  
  22. Object result = null;   
  23.  
  24. Throwable ex = null;   
  25.  
  26. InvokeJniInfo invInfo = new InvokeJniInfo(proxy,method,args,result,ex);   
  27.  
  28. log.debug("Invoking Before Intercepors!");   

//实现方法调用之前进行拦截的方法

  1. invokeInterceptorBefor(invInfo);   
  2.  
  3.  
  4. try{   
  5.  
  6. log.debug("Invoking Proxy Method!");   
  7.  
  8. //调用方法   
  9.  
  10. result = method.invoke(orginalObject,args);   
  11.  
  12.  
  13. invInfo.setResult(result);   
  14.  
  15. log.debug("Invoking After method!");   

//实现方法调用之后进行拦截的方法

  1. invokeInterceptorAfter(invInfo);   
  2.  
  3.  
  4. }catch(Throwable tr){   
  5.  
  6. invInfo.setException(tr);   
  7.  
  8. log.error("Invoking exceptionThrow method!");   

//实现出现异常进行拦截的方法

  1. invokeInterceptorExceptionThrow(invInfo);   
  2.  
  3. }   
  4.  
  5. return result;   
  6.  
  7. }   

//获取拦截器列表

  1. private synchronized List getIntercetors(){   
  2.  
  3. if(null == interceptors){   
  4.  
  5. interceptors = new ArrayList();   

//添加日志记录拦截器

  1. interceptors.add(new LogInterceptor());  

//添加初始化JavaBean拦截器

  1. interceptors.add(new InitParamsInterceptor());  

//如果需要添加其他功能,可以很方便的添加其他的拦截器实现功能

  1. }   
  2.  
  3. return interceptors;   
  4.  
  5. }   
  6.  
  7. private void invokeInterceptorBefor(InvokeJniInfo invInfo){   
  8.  
  9. List interceptors = getIntercetors();   
  10.  
  11. int len = interceptors.size();   

//遍历所有拦截器,并调用拦截器的before方法

  1. for(int i = 0;i((Interceptor)interceptors.get(i)).before(invInfo);   
  2.  
  3. }   
  4.  
  5. }   
  6.  
  7.  
  8. private void invokeInterceptorAfter(InvokeJniInfo invInfo){   
  9.  
  10. List interceptors = getIntercetors();   
  11.  
  12. int len = interceptors.size();   

//遍历所有拦截器,并调用拦截器的after方法

  1. for(int i = len - 1;i >= 0;i--){   
  2.  
  3. ((Interceptor)interceptors.get(i)).after(invInfo);   
  4.  
  5. }   
  6.  
  7. }   
  8.  
  9.  
  10. private void invokeInterceptorExceptionThrow(InvokeJniInfo invInfo){   
  11.  
  12. List interceptors = getIntercetors();   
  13.  
  14. int len = interceptors.size();   

//遍历所有拦截器,并调用拦截器的exceptionThrow方法

  1. for(int i = len - 1;i >= 0;i--){   
  2.  
  3. ((Interceptor)interceptors.get(i)).exceptionThrow(invInfo);   
  4.  
  5. }   
  6.  
  7. }   
  8.  
  9. }   

7.获取动态代理对象工厂InterceptorFactory

  1. public class InterceptorFactory {   
  2.  
  3. private static Log log = LogFactory.getLog(InterceptorFactory.class);   
  4.  
  5. public static Object getClassInstance(String clzName) {   
  6.  
  7. Class cls;   
  8.  
  9. Object obj = null;   
  10.  
  11. try {   
  12.  
  13. cls = Class.forName(clzName);   
  14.  
  15. obj = (Object) cls.newInstance();   
  16.  
  17. } catch (Exception e) {   
  18.  
  19. log.error(e.getStackTrace());   
  20.  
  21. }   
  22.  
  23. return obj;   
  24.  
  25. }   
  26.  
  27. public static Object getInterceptorProxyedObject(String clzName) {   
  28.  
  29. InterceptorHandler aopHandler = new InterceptorHandler();   
  30.  
  31. Object obj = getClassInstance(clzName);   
  32.  
  33. return aopHandler.bind(obj);   
  34.  
  35. }   
  36.  
  37. }   
  38.  
  39.  
  40. 8.修改以前的代码,使用动态代理实现   
  41.  
  42. public class SOAP{   
  43.  
  44. private JniInterface jni = null;   
  45.  
  46. private Log log = 。。。;   
  47.  
  48. public SOAP(){   
  49.  
  50. jni=(JniInterface)InterceptorFactory.getInterceptorProxyedObject("JniClass");   
  51.  
  52. }   
  53.  
  54.  
  55. /**方法A**/   
  56.  
  57. public JavaBeanA aMethod(JavaBeanA javaBeanA){   
  58.  
  59. return jni.aMethod(javaBeanA);   
  60.  
  61. }   

……………………………………

……………………………………

等等,很多这样的方法

……………………………………

……………………………………

}


从红色代码对比可以看出,省了很多代码。

三、总结

1.必须彻底贯彻针对接口编成这一编程思想。

2.明白了这个,是不是也明白了Spring的AOP的实现了?以及为什么要使用Spring的AOP的时候必须使用他的BeanFactory呢?

【编辑推荐】

  1. Java连接MySQL中文乱码处理
  2. 在Java应用程序中使用Jfreechart配置
  3. Java虚拟机内部构成浅析
  4. 浅谈Java线程的生命周期
  5. 关于Java继承的一些复习
责任编辑:张燕妮 来源: 赛迪网
相关推荐

2022-02-08 17:07:54

Spring BooSpring Aop日志记录

2023-11-07 16:00:25

面向切面编程开发

2010-04-26 08:53:06

面向方面编程.NET

2021-07-14 11:07:56

AOPJDKCglib

2015-09-28 15:59:00

Java动态代理机制

2015-09-22 11:09:47

Java 8动态代理

2023-03-30 07:48:46

接口鉴权SpringBoot

2022-09-01 10:40:29

SpringAOPJDK

2017-05-11 21:30:01

Android动态代理ServiceHook

2021-03-22 08:45:30

异步编程Java

2023-03-16 07:52:47

Golang函数式编程

2011-04-06 11:41:25

Java动态代理

2013-06-14 11:18:41

Fedora Gnu PG 代理

2012-08-28 10:59:26

JavaJava动态代理Proxy

2011-12-08 10:24:53

JavaNIO

2017-10-12 14:56:11

2011-03-23 10:40:51

java代理模式

2023-10-20 09:32:25

Java技术

2023-12-06 08:23:44

代理模式设计模式

2021-07-06 06:39:22

Java静态代理动态代理
点赞
收藏

51CTO技术栈公众号