TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
1.首先实际的业务处理,由于采用动态代理(AOP思想)所以,必须基于接口编程.
package proxy;
public interface BusinessInterface {
public void processBusiness();
public int add(int a,int b);
}
2.实现具体业务的实现类
package proxy;
public class BusinessImpl implements BusinessInterface {
public void processBusiness() {
System.out.println("-----------processBusiness");
}
public int add(int a,int b)
{
System.out.println("result="+(a+b));
return a+b;
}
}
3.InvocationHandler接口提供一个执行处理器,然后通过java.lang.reflect.Proxy得到一个
代理对象,通过这个代理对象来执行商业
package proxy; import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.logging.Logger; /**
* 日志代理处理器
* InvocationHandler接口提供了一个执行处理器
*/
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...");
}
return o;
}
}
4.测试类
package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class Test {
public static void main(String[] args) {
// 具体实现类
BusinessInterface businessImp = new BusinessImpl();
// 动态代理执行处理器
InvocationHandler handler = new LogHandler(businessImp);
// 代理对象
BusinessInterface proxy = (BusinessInterface) Proxy.newProxyInstance(
businessImp.getClass().getClassLoader(), businessImp.getClass()
.getInterfaces(), handler);
// 由代理对象来执行商业方法
// 在商业方法被调用的同时,执行处理器会被自动调用
proxy.processBusiness();
proxy.add(1, 2);
}
} 运行结果:
C:java>java Test
2006-4-5 16:56:13 LogHandler invoke
信息: method stats...public abstract void BusinessInterface.processBusiness()
-----------processBusiness
2006-4-5 16:56:15 LogHandler invoke
信息: method ends...public abstract void BusinessInterface.processBusiness()
2006-4-5 16:56:15 LogHandler invoke
信息: method stats...public abstract int BusinessInterface.add(int,int)
result=3
2006-4-5 16:56:15 LogHandler invoke
信息: method ends...public abstract int BusinessInterface.add(int,int) C:java>
源码下载:http://file.javaxxz.com/2014/10/28/235731968.zip |
|