用reflect proxy把你的商業方法執行推遲,並放到其他地方執行。
概念:1.proxy instance 代理實例
2.invocationHandler 調用處理器
編寫商業對象和接口:
public interface BusinessInterface
{
public void processBusiness();
}
public class BusinessObject implements BusinessInterface
{
public void processBusiness(){
System.out.println("this is the business code!");
}
};
編寫調用處理器,商業方法就在這裏被調用:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
public class Myhandler implements InvocationHandler
{
Object businessObject;
Myhandler(Object delegate){
businessObject = delegate;
}
public Object invoke(Object proxy , Method method , Object[] args) throws IllegalAccessException ,InvocationTargetException{
Object o = null;
System.out.println("log: start execute business");//這裏可以用log4j,那麼記錄日誌就和商業方法分開了
//if(IsPermission(user)){//可以考慮在這裏進行安全控制
//Transaction.begin();//可以考慮在這裏進行事務處理控制
//long begin = System.CurrentTimeMillis();
o = method.invoke(businessObject,args);//執行商業方法
//long end = System.CurrenTimeMillis();
//System.out.println(">>log:"+ (end - begin));//進行性能統計,
//Transaction.commit();//
//}
System.out.println("log: end execute business");
return o;
}
};
構造代理實例並用代理實例來執行商業方法
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class AoP
{
public static void main(String[] args)
{
BusinessInterface businessObject = new BusinessObject();
//構造一個handler
InvocationHandler handler = new Myhandler(businessObject);
//構造代理實例
BusinessInterface proxy = (BusinessInterface)Proxy.newProxyInstance(businessObject.getClass().getClassLoader(),businessObject.getClass().getInterfaces(),handler);
//用代理實例來執行商業方法,那麼代理會調用myhandler的invoke()來執行這個方法
proxy.processBusiness();
}
}