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);
}
}