licheng700

BlogJava 首页 新随笔 联系 聚合 管理
  26 Posts :: 5 Stories :: 5 Comments :: 1 Trackbacks

1.首先实际的业务处理,由于采用动态代理(AOP思想)所以,必须基于接口编程.
   package proxy;
public interface BusinessInterface {
 public void processBusiness();
 public int add(int a,int b);
}
2.实现具体业务的实现类
package proxy;
public class BusinessImpl implements BusinessInterface {
 public void processBusiness() { 
  System.out.println("-----------processBusiness");
 }
 public int add(int a,int b)
 {
  System.out.println("result="+(a+b));
  return a+b;
 }
}
3.InvocationHandler接口提供一个执行处理器,然后通过java.lang.reflect.Proxy得到一个
代理对象,通过这个代理对象来执行商业
 package proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.logging.Logger;

/**
 * 日志代理处理器
 * InvocationHandler接口提供了一个执行处理器
 */
public class LogHandler implements InvocationHandler {

 private Logger logger = Logger.getLogger(this.getClass().getName());

 private Object delegate;

 public LogHandler(Object delegate) {
  this.delegate = delegate;
 }

 public Object invoke(Object proxy, Method method, Object[] args)
   throws Throwable {
  Object o = null;
  try {
   logger.info("method stats..." + method);
   o = method.invoke(delegate, args);
   logger.info("method ends..." + method);
  } catch (Exception e) {
   logger.info("Exception happends...");   
  }
  return o;
 }
}
4.测试类
package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class Test {
 public static void main(String[] args) {
  // 具体实现类
  BusinessInterface businessImp = new BusinessImpl();
  // 动态代理执行处理器
  InvocationHandler handler = new LogHandler(businessImp);
  // 代理对象
  BusinessInterface proxy = (BusinessInterface) Proxy.newProxyInstance(
    businessImp.getClass().getClassLoader(), businessImp.getClass()
      .getInterfaces(), handler);
  // 由代理对象来执行商业方法
  // 在商业方法被调用的同时,执行处理器会被自动调用
  proxy.processBusiness();
  proxy.add(1, 2);
 }
}

posted on 2005-09-22 15:30 小海船 阅读(295) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: