天天看點

不使用spring的aop功能實作日志輸出

第一種:

public class TimeBook {

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

 //稽核資料的相關程式

 public void doAuditing(String name){

  logger.log(Level.INFO, name + "開始稽核資料...");

  System.out.println("稽核程式");

  logger.log(Level.INFO, name + "稽核資料結束...");

 }

}

//TestHelloWorld.java

package com.gc.test;

import com.gc.action.TimeBook;

public class TestHelloWorld {

 public static void main(String[] args){

  TimeBook timeBook = new TimeBook();

  timeBook.doAuditing("張三");

 }

}

第二種:通過面向接口程式設計實作日志輸出

public class TimeBook implements TimeBookInterface {

 //稽核資料的相關程式

 public void doAuditing(String name){

  System.out.println("稽核程式");

 }

}

//TimeBookProxy.java

package com.gc.action;

import org.apache.log4j.Level;

import org.apache.log4j.Logger;

import com.gc.impl.TimeBookInterface;

public class TimeBookProxy {

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

 private TimeBookInterface timeBookInterface;

 //在該類中針對前面的接口TimeBookInterface程式設計,而不是針對具體的類

 public TimeBookProxy(TimeBookInterface timeBookInterface){

  this.timeBookInterface = timeBookInterface;

 }

 //實際業務處理

 public void doAuditing(String name){

  logger.log(Level.INFO,"開始稽核資料 "+name);

  timeBookInterface.doAuditing(name);

  logger.log(Level.INFO,"稽核資料結束 "+name);

 }

}

public class TestHelloWorld {

 public static void main(String[] args){

  TimeBookProxy timeBookProxy = new TimeBookProxy(new TimeBook());

  timeBookProxy.doAuditing("張三");

 }

}

第三種:使用java的代理機制進行日志輸出

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,args[0]+" 稽核資料結束...");

  }catch(Exception e){

   logger.log(Level.INFO,e.toString());

  }

  return result;

 }

}

//TimeBookInterface.java

package com.gc.impl;

//針對接口程式設計

public interface TimeBookInterface {

 public void doAuditing(String name);

}

//TimeBook.java

public class TimeBook implements TimeBookInterface {

 //稽核資料的相關程式

 public void doAuditing(String name){

  System.out.println("稽核程式");

 }

}

//TestHelloWorld.java

public class TestHelloWorld {

 public static void main(String[] args){

  //實作了對日志類的重用

  LogProxy logProxy = new LogProxy();

  TimeBookInterface timeBookProxy = (TimeBookInterface)logProxy.bind(new TimeBook());

  timeBookProxy.doAuditing("張三");

 }

}

繼續閱讀