import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyTest {
// jdk代理接口
interface BaseInterface {
public void test();
}
//被代理类
public static class BaseEntity implements BaseInterface {
@Override
public void test() {
System.out.println(1111111);
}
}
public static void main(String[] args) {
// cglib();
// jdk();
proxyFactory();
}
// cglib代理
public static void cglib() {
BaseEntity target = new BaseEntity();
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(BaseEntity.class);
enhancer.setCallbacks(new Callback[]{
new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("-111111");
method.invoke(target, objects);
System.out.println("+111111");
return null;
}
}
});
BaseEntity baseEntity = (BaseEntity) enhancer.create();
baseEntity.test();
}
// jdk代理
public static void jdk() {
BaseEntity target = new BaseEntity();
Object o = Proxy.newProxyInstance(ProxyTest.class.getClassLoader(), new Class[]{BaseInterface.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("-111111");
Object invoke = method.invoke(target, args);
System.out.println("+111111");
return invoke;
}
});
BaseInterface baseEntity = (BaseInterface) o;
baseEntity.test();
}
// spring proxyFactory代理
public static void proxyFactory() {
BaseEntity target = new BaseEntity();
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setTarget(target);
// proxyFactory.setInterfaces(BaseInterface.class); //此处可以控制走jdk还是cglib 这只是场景之一
// proxyFactory.addInterface(BaseInterface.class);
proxyFactory.addAdvice(new org.aopalliance.intercept.MethodInterceptor() {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println("-111111");
Object proceed = methodInvocation.proceed();
System.out.println("+111111");
return proceed;
}
});
BaseInterface baseEntity = (BaseInterface) proxyFactory.getProxy();// jdk只能是接口 cglib两者都可以
baseEntity.test();
}
}
java代理小记
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 总结了一些爬虫代理的资料和知识,并尝试使用asyncio和aiohttp使用代理ip访问目标网站,按代理IP的访问...
- Nginx简介 Nginx (engine x) 是一个高性能的HTTP和反向代理web服务器,同时也提供了IMA...
- 最近在学习Java反射的一些知识,看到了一些有关代理的例子,好记性不如烂笔头,所以这里将它记录下来。接下来话不多说...