通过面向接口编程实现日志输出
(1)建立一个接口TimeBookInterface,代码如下
/*******TimeBookInterface.java********/
package com.gc.dao;
public interface TimeBookInterface{
public void doAuditing(String name);
}
(2)编写接口实现类,代码如下
/*******TimeBook.java********/
package com.gc.dao.impl;
public class TimeBook implements TimeBookInterface{
public void doAuditing(String name){
//审查数据的相关程序
......
}
}
(3)编写一个代理类,用来实现日志输出,其代码如下
/*******TimeBookProxy.java********/
package com.gc.dao.impl;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
public class TimeBookProxy{
private Logger logger = Logger.getLogger(this.getClass().getName());
private 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+"审核数据结束");
}
}
(4)编写测试代码类
......
public static void main(String[] args){
//针对接口进行编程
TimeBookProxy timeBookProxy = new TimeBookProxy(new TimeBook());
timeBookProxy.doAuditing("张三");
}
使用java的代理机制进行日志输出
(1)编写一个日志信息的代理类LogProxy,这个代理类实现了接口InvocationHandler,
可以对任何接口实现日志信息的输出.其代理如下
package com.gc.dao;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
//代理类实现了接口InvocationHandler
public class LogProxy implements InvocationHandler{
private Logger logger = Logger.getLogger(this.getClass().getName());
private Object delegate;
//绑定对象
public Object bing(Object delegate){
this.delegate = delegate;
return Proxy.new ProxyInstance(delegate.getClass().getClassLoader(),delegate.getClass().getInterfaces(),this);
}
//针对接口编程
public Object invoke(Object proxy,Mehtod 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;
}
}
(2)建立一个接口TimeBookInterface,代码如下
/*******TimeBookInterface.java********/
package com.gc.dao;
public interface TimeBookInterface{
public void doAuditing(String name);
}
(3)编写接口实现类,代码如下
/*******TimeBook.java********/
package com.gc.dao.impl;
public class TimeBook implements TimeBookInterface{
public void doAuditing(String name){
//审查数据的相关程序
......
}
}
(4)编写测试代码类
......
public static void main(String[] args){
//实现了对日志类的重用
LogProxy logProxy = new LogProxy();
TimeBookInterface timeBookInterface = (TimeBookInterface)logProxy.bind(new TimeBook());
timeBookProxy.doAuditing("张三");
}
代码来自spring从入门到精通一书
posted on 2007-08-25 14:21
Ke 阅读(572)
评论(0) 编辑 收藏 所属分类:
spring