spring中的代理
1.静态代理:
public class Main2 {
//这里传入的是接口类型的对象,方便向上转型,实现多态
public static void consumer(ProxyInterface pi){
pi.say();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
consumer(new ProxyObject());
}
}
//代理接口
interface ProxyInterface{
public void say();
}
//被代理者
class RealObject implements ProxyInterface{
//实现接口方法
@Override
public void say() {
// TODO Auto-generated method stub
System.out.println("say");
}
}
//代理者
class ProxyObject implements ProxyInterface{
@Override
public void say() {
// TODO Auto-generated method stub
//dosomething for example
System.out.println("hello proxy");
new RealObject().say();
System.out.println("this is method end");
}
}
hello proxy
say
this is method end
控制台输出:
hello proxy
say
this is method end
2.动态代理:
package docker.demo;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @program:dockerdemo
* @desc:
* @author:qiyihang
* @date:2020/12/15
*/
public class DynamicProxy {
static void customer(ProxyInterface pi){
pi.say();
}
public static void main(String[] args){
RealObject real = new RealObject();
ProxyInterface proxy = (ProxyInterface) Proxy.newProxyInstance(ProxyInterface.class.getClassLoader(),new Class[]{ProxyInterface.class}, new ProxyObject(real));
customer(proxy);
}
}
interface ProxyInterface{
void say();
}
//被代理类
class RealObject implements ProxyInterface{
public void say(){
System.out.println("i'm talking");
}
}
//代理类,实现InvocationHandler 接口
class ProxyObject implements InvocationHandler {
private Object proxied = null;
public ProxyObject(){
}
public ProxyObject(Object proxied){
this.proxied = proxied;
}
public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable {
System.out.println("hello");
return arg1.invoke(proxied, arg2);
};
}
控制台输出:
hello
i’m talking
代理类实现了InvocationHandler
接口,
ProxyInterface proxy = (ProxyInterface) Proxy.newProxyInstance(ProxyInterface.class.getClassLoader(),new Class[]{ProxyInterface.class}, new ProxyObject(real));
得到接口的实例,作为参数传递到customer()
,这里每一个在代理类上处理的东西也会被重定向到调用处理器上。
Proxy.newProxyInstance()
方法,接收三个参数:第一个参数指定当前目标对象使用的类加载器,获取加载器的方法是固定的;第二个参数指定目标对象实现的接口的类型;第三个参数指定动态处理器,执行目标对象的方法时,会触发事件处理器的方法。
源码分析之后补上,先做个记录
摘抄自: Java动态代理与反射详解
还没有评论,来说两句吧...