java | 代理 | AOP
public void processBusiness(); //商业过程接口 } //实现该接口的类,代表了代理模式中"真实角色"的类 public class BusinessObject implements Business {
private Logger log = Logger.getLogger(this.getClass().getName());
public void processBusiness(){
//business processing
System.out.println(“here is business logic”);
}
}
//代理角色的类 public class ProxyBusiness implements Business{ private Logger log = Logger.getLogger(this.getClass().getName()); BusinessObject busiObj=new BusinessObject(); public void processBusiness(){ log.info("method stats... "); busiObj.processBusiness(); log.info("method ends... "); } }
通过实现java.lang.reflect.InvocationHandler接口提供一个执行处理器,然后通过java.lang.reflect.Proxy得到一个代理对象,通过这个代理对象来执行商业方法,在商业方法被调用的同时,执行处理器会被自动调用. 我们所要做的仅仅是提供一个处理器. import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.logging.Logger; public class LogHandler implements InvocationHandler {
private Logger log = 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 obj = null;
try {
log.info("method stats..." + method);
obj = method.invoke(delegate,args);
log.info("method ends..." + method);
} catch (Exception e){
log.info("Exception happends...");
//excetpion handling.
}
return obj;
}
}
} 客户端调用商业方法的代码如下:
Business businessImp = new BusinessObject();
InvocationHandler handler = new LogHandler(businessImp);
Business proxy = (Business) Proxy.newProxyInstance(
businessImp.getClass().getClassLoader(),
businessImp.getClass().getInterfaces(),
handler);
proxy.processBusiness();
程序输出如下:
INFO: method stats...
here is business logic
INFO: method ends...
Spring入门第三讲 Spring中的代理 静态代理 动态代理(JDK代理) cglib代理(字节码增强) Spring中的AOPspring的静态代理和动态代理
SpringAOP用到了什么代理,以及动态代理与静态代理的区别springaop静态代理和动态代理
Spring中AOP的两种代理方式(Java动态代理和CGLIB代理)spring aop与动态代理
代理模式-静态代理模式 代理模式-动态代理(基于接口,JDK动态代理)动态代理是代理模式吗
【设计模式】代理模式 ( 动态代理使用流程 | 创建目标对象 | 创建被代理对象 | 创建调用处理程序 | 动态创建代理对象 | 动态代理调用 )动态代理是代理模式吗
动态与代理AOP--01【代理的作用与概念】【动态代理与AOP】