Java代理详话简说

canca canca
2007-08-29 11:14
2
0

        Java的代理,使项目实现低藕合成为可能。Spring框架中的AOP,内部就是用Java代理来实现。因此,认识JAVA代理原理对学习学Spring AOP是有密切关系的。

       现在举了J2EE中的例子:如何实现日志与逻辑代码相分离呢?以下这个例子就能办到。当然,用Spring是正选。这里只是对JAVA中的代理做个解说而己。

package com.gc.action;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class LogProxy implements InvocationHandler {
 private Logger logger = Logger.getLogger(this.getClass().getName());
 private Object delegate;
 //绑定代理对象
 public Object bind(Object delegate){
  this.delegate = delegate;
  return Proxy.newProxyInstance(delegate.getClass().getClassLoader(), delegate.getClass().getInterfaces(), this);
 }
 public Object invoke(Object proxy,Method method,Object[] args) throws Throwable{
  Object result = null;
  try{
   //在方法调用前后进行日志输出
   logger.log(Level.INFO,args[0] + " 开始审核数据....");
   result = method.invoke(delegate,args);
   logger.log(Level.INFO, " 审核数据结束....");
  }catch(Exception ex){
   logger.log(Level.INFO,ex.toString());
  }
  return result;
 }

代码,不难理解固此没加上什么注释...
 
}

发表评论