java | 代理 | AOP

来源:互联网 发布:诸神黄昏女神进阶数据 编辑:程序博客网 时间:2024/05/21 10:24

AOP(Aspect Oriented Programing)面向切面编程. 支持AOP的框架(Framework)有Spring,JAC,Jboss AOP等.AOP的应用范围有日志记录,性能统计,安全控制,事务处理等方面.它的主要意图就是将日志记录,性能统计,安全控制等等代码从商业逻辑代码中清楚的划分出来.通过这些行为的分离,我们希望可以将它独立的配置到商业方法中去,而要改变这种行为也不影响到商业逻辑代码.

java语言本身自带有动态代理功能,可以实现AOP.

例子:

public interface Business{
 public void processBusiness(); //商业过程接口

}

//实现该接口的类,代表了代理模式中"真实角色"的类

public class BusinessObject implements Business {

 private Logger log = Logger.getLogger(this.getClass().getName());
 public void processBusiness(){
  //business processing
  System.out.println(“here is business logic”);
 }
}

//代理角色的类

public class ProxyBusiness implements Business{

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

       BusinessObject    busiObj=new  BusinessObject();

       public void processBusiness(){

              log.info("method stats... ");

              busiObj.processBusiness();

             log.info("method ends... ");

        }

}

通过实现java.lang.reflect.InvocationHandler接口提供一个执行处理器,然后通过java.lang.reflect.Proxy得到一个代理对象,通过这个代理对象来执行商业方法,在商业方法被调用的同时,执行处理器会被自动调用.

我们所要做的仅仅是提供一个处理器.

import  java.lang.reflect.InvocationHandler;

import  java.lang.reflect.Method;

import  java.util.logging.Logger;

public class LogHandler implements InvocationHandler {

 private Logger log = 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 obj = null;
  try {
   log.info("method stats..." + method);
   obj = method.invoke(delegate,args);
   log.info("method ends..." + method);
  } catch (Exception e){
   log.info("Exception happends...");
   //excetpion handling.
  }
  return obj;
 }

 
}

客户端调用商业方法的代码如下:

Business businessImp = new BusinessObject();

InvocationHandler handler = new LogHandler(businessImp);

Business proxy = (Business) Proxy.newProxyInstance(
 businessImp.getClass().getClassLoader(),
 businessImp.getClass().getInterfaces(),
 handler);

proxy.processBusiness();

程序输出如下:

INFO: method stats...
here is business logic
INFO: method ends...


原创粉丝点击