一、AOP代理工厂
代码分支:proxy-factory
增加AOP代理工厂ProxyFactory,由AdvisedSupport#proxyTargetClass属性决定使用JDK动态代理还是CGLIB动态代理。
测试:
public class DynamicProxyTest {
private AdvisedSupport advisedSupport;
@Before
public void setup() {
WorldService worldService = new WorldServiceImpl();
advisedSupport = new AdvisedSupport();
TargetSource targetSource = new TargetSource(worldService);
WorldServiceInterceptor methodInterceptor = new WorldServiceInterceptor();
MethodMatcher methodMatcher = new AspectJExpressionPointcut("execution(* org.springframework.test.service.WorldService.explode(..))").getMethodMatcher();
advisedSupport.setTargetSource(targetSource);
advisedSupport.setMethodInterceptor(methodInterceptor);
advisedSupport.setMethodMatcher(methodMatcher);
}
@Test
public void testProxyFactory() throws Exception {
// 使用JDK动态代理
advisedSupport.setProxyTargetClass(false);
WorldService proxy = (WorldService) new ProxyFactory(advisedSupport).getProxy();
proxy.explode();
// 使用CGLIB动态代理
advisedSupport.setProxyTargetClass(true);
proxy = (WorldService) new ProxyFactory(advisedSupport).getProxy();
proxy.explode();
}
}
ProxyFactory:
public class ProxyFactory {
private AdvisedSupport advisedSupport;
public ProxyFactory(AdvisedSupport advisedSupport) {
this.advisedSupport = advisedSupport;
}
public Object getProxy() {
return createAopProxy().getProxy();
}
private AopProxy createAopProxy() {
if (advisedSupport.isProxyTargetClass()) {
return new CglibAopProxy(advisedSupport);
}
return new JdkDynamicAopProxy(advisedSupport);
}
}
我们总结一下上面代码的步骤:
二、看一下cglib动态代理,和jdk动态代理创建代理的方法
2.1 cglib动态代理
和之前的一样,使用Enhancer

2.2 jdk动态代理(默认)
![bJ-1773071436209)]](https://www.171host.com/wp-content/uploads/2026/03/20260309163439-69aef69f8c2aa.png)
这里的h参数,指的就是InvocationHandler,也就是当前对象JdkDynamicAopProxy;后续是调用了JdkDynamicAopProxy内部的invoke方法,从而实现了代理的功能

