动态代理设计模式
1、动态代理设计模式 解决得业务问题:每个方法前置日志和后置日志 即执行顺序为: 1、输出执行程序前日志 2、执行业务代码 3、执行完业务代码之后得日志 代码: package proxy.service; import proxy.service.impl.InfoServiceImpl; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class ServiceProxy { public static void main(String[] args) { InfoSevice infoSevice=new InfoServiceImpl(); InfoSevice newInfoService =(InfoSevice) Proxy.newProxyInstance( infoSevice.getClass().getClassLoader(), infoSevice.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 1、log入口 long start = System.currentTimeMillis(); System.out.println(String.format("%s start...",method.getName())); // 2、执行业务代码 Object response = method.invoke(infoSevice, args); //3、出口 long end = System.currentTimeMillis(); System.out.println(String.format("%s end",method.getName())); System.out.println("costtime" + (end - start)); return response; } } ); newInfoService.deleteinfo(); } } 2、动态代理封装,兼容代理所有得sevice (1)封装一个类实现InvocationHandler接口,兼容所有传入得service都能置前和置后输出日志 package proxy.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class LogPrintHandler implements InvocationHandler { private Object proxyObj; public LogPrintHandler(Object proxyObj){ this.proxyObj=proxyObj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //1、log入口 System.out.println(String.format("%s...start",method.getName())); //2、执行业务代码 Object reponse = method.invoke(proxyObj, args); //3、日志出口 System.out.println(String.format("%s...end",method.getName())); return reponse; } } (2)封装一个控制代理得方法,参数接收传service对应得实现类 package proxy.proxy; import java.lang.reflect.Proxy; public class ServiceProxyHandler { public ServiceProxyHandler(){ } public static<T> T proxyService(Object service){ return (T) Proxy.newProxyInstance( service.getClass().getClassLoader(), service.getClass().getInterfaces(), new LogPrintHandler(service) ); } } (3)封装动态代理模式测试 package proxy; import proxy.proxy.ServiceProxyHandler; import proxy.service.InfoSevice; import proxy.service.MsgService; import proxy.service.ServiceProxy; import proxy.service.impl.InfoServiceImpl; import proxy.service.impl.MsgServiceImpl; public class App { public static void main(String[] args) { InfoSevice infoSevice=ServiceProxyHandler.proxyService(new InfoServiceImpl()); infoSevice.addinfo(); MsgService msgService= ServiceProxyHandler.proxyService(new MsgServiceImpl()); msgService.quarymsg(""); } }