不使用spring的aop功能实现日志输出

时间:2022-10-17 06:15:45

第一种:

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("张三");
 }
}



相关文章