欢迎光临
我们一直在努力

mini-spring基础篇:AOP(四):AOP代理工厂

一、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);
}
}

我们总结一下上面代码的步骤:

  • 组织AdvisedSupport对象:AdvisedSupport对象可以简单的概况为切点、切点对应的方法、目标类、拦截器等;(setup方法)
  • 设置代理类型:在AdvisedSupport对象里设置是否cglib动态代理(默认);
  • 新建代理工厂:新建ProxyFactory对象,把对象传到代理工厂里;
  • 获取代理类:由ProxyFactory获取代理类,由【第2步】设置的属性,觉得走哪种代理类型;
  • 执行方法:执行代理类的explode方法;
  • 二、看一下cglib动态代理,和jdk动态代理创建代理的方法

    2.1 cglib动态代理

    和之前的一样,使用Enhancer

    在这里插入图片描述

    2.2 jdk动态代理(默认)

    bJ-1773071436209)]

    这里的h参数,指的就是InvocationHandler,也就是当前对象JdkDynamicAopProxy;后续是调用了JdkDynamicAopProxy内部的invoke方法,从而实现了代理的功能

    赞(0)
    未经允许不得转载:171主机测评 » mini-spring基础篇:AOP(四):AOP代理工厂
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址