public interface BusinessInterface { public void processBusiness(); } public class BusinessObject implements BusinessInterface { private Logger logger = Logger.getLogger(this.getClass().getName()); public void processBusiness(){ try { logger.info("start to processing..."); //business logic here. System.out.println(“here is business logic”); logger.info("end processing..."); } catch (Exception e){ logger.info("exception happends..."); //exception handling } } } |
这里处理商业逻辑的代码和日志记录代码混合在一起,这给日后的维护带来一定的困难,并且也会造成大量的代码重复。完全相同的log代码将出现在系统的每一个BusinessObject中。
按照AOP的思想,我们应该把日志记录代码分离出来。要将这些代码分离就涉及到一个问题,我们必须知道商业逻辑代码何时被调用,这样我们好插入日志记录代码。一般来说要截获一个方法,我们可以采用回调方法或者动态代理。动态代理一般要更加灵活一些,目前多数的AOP Framework也大都采用了动态代理来实现。这里我们也采用动态代理作为例子。
JDK1.2以后提供了动态代理的支持,程序员通过实现java.lang.reflect.InvocationHandler接口提供一个执行处理器,然后通过java.lang.reflect.Proxy得到一个代理对象,通过这个代理对象来执行商业方法,在商业方法被调用的同时,执行处理器会被自动调用。
有了JDK的这种支持,我们所要做的仅仅是提供一个日志处理器。
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..."); //excetpion handling. } return o; } } |
public class BusinessObject implements BusinessInterface { private Logger logger = Logger.getLogger(this.getClass().getName()); public void processBusiness(){ //business processing System.out.println(“here is business logic”); } } |
BusinessInterface businessImp = new BusinessObject(); InvocationHandler handler = new LogHandler(businessImp); BusinessInterface proxy = (BusinessInterface) Proxy.newProxyInstance( businessImp.getClass().getClassLoader(), businessImp.getClass().getInterfaces(), handler); proxy.processBusiness(); |
INFO: method stats... here is business logic INFO: method ends... |
……