Spring 关于动态代理

来源:互联网 发布:屏幕校准软件 编辑:程序博客网 时间:2024/05/14 18:58

   动态代理 机制主要实现是一个代理类java.lang.reflect.Proxy类和java.lang.reflect.InvocationHandler接口。

 

 

例如 有一个业务接口类

import org.apache.log4j.Level;

public interface TimeBookInterface {
  public void doAuditing(String name);

}

 

//接口实现类

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

import com.gc.impl.TimeBookInterface;

public class TimeBook implements TimeBookInterface {
 private Logger logger = Logger.getLogger(this.getClass().getName());
   public void doAuditing(String name){
   
 //   logger.log(Level.INFO,name+" 开始审核数据....");
   
   
    logger.log(Level.INFO,name+" 正在审核数据....");
   }
}

 

 

 

// 代理类

 

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 invoke(Object proxy, Method method, Object[] args)
   throws Throwable {
  // TODO Auto-generated method stub
  Object result = null;
  try
  {
   logger.log(Level.INFO,args[0]+" 开始审核数据..."); 
            result = method.invoke(delegate, args);
            logger.log(Level.INFO,args[0]+" 审核数据结束...");
  }catch(Exception e){
   logger.log(Level.INFO,e.toString());
   
  }
  return result;
 }
 public Object bind(Object delegate){
  this.delegate = delegate;
  return Proxy.newProxyInstance(delegate.getClass().getClassLoader(), delegate.getClass().getInterfaces(), this);
 }
 
 

}

 

 

//测试代码

 

 

 

import com.gc.action.TimeBook;
import com.gc.impl.TimeBookInterface;

public class TEST {
  public static void main(String args[]){
   // 代理类
   LogProxy logProxy = new LogProxy();
   TimeBookInterface timBookInterface = (TimeBookInterface)logProxy.bind(new TimeBook());
   timBookInterface.doAuditing("张三");
  }
}

 

 

原创粉丝点击