1.首先實(shí)際的業(yè)務(wù)處理,由于采用動(dòng)態(tài)代理(AOP思想)所以,必須基于接口編程.
package proxy;
public interface BusinessInterface {
public void processBusiness();
public int add(int a,int b);
}
2.實(shí)現(xiàn)具體業(yè)務(wù)的實(shí)現(xiàn)類(lèi)
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接口提供一個(gè)執(zhí)行處理器,然后通過(guò)java.lang.reflect.Proxy得到一個(gè)
代理對(duì)象,通過(guò)這個(gè)代理對(duì)象來(lái)執(zhí)行商業(yè)
package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.logging.Logger;
/**
* 日志代理處理器
* InvocationHandler接口提供了一個(gè)執(zhí)行處理器
*/
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.測(cè)試類(lèi)
package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class Test {
public static void main(String[] args) {
// 具體實(shí)現(xiàn)類(lèi)
BusinessInterface businessImp = new BusinessImpl();
// 動(dòng)態(tài)代理執(zhí)行處理器
InvocationHandler handler = new LogHandler(businessImp);
// 代理對(duì)象
BusinessInterface proxy = (BusinessInterface) Proxy.newProxyInstance(
businessImp.getClass().getClassLoader(), businessImp.getClass()
.getInterfaces(), handler);
// 由代理對(duì)象來(lái)執(zhí)行商業(yè)方法
// 在商業(yè)方法被調(diào)用的同時(shí),執(zhí)行處理器會(huì)被自動(dòng)調(diào)用
proxy.processBusiness();
proxy.add(1, 2);
}
}