ProxyFactory 源码分析

介绍


spring 提供的编程式aop实现,即通过 ProxyFactory类完成的。

举例
@Test
public void testRemoveAdvisorByReference() {
    //被代理的对象
    TestBean target = new TestBean();
    //代理工厂
    ProxyFactory pf = new ProxyFactory(target);
    //拦截器1
    NopInterceptor nop = new NopInterceptor();
    //拦截器2
    CountingBeforeAdvice cba = new CountingBeforeAdvice();
    //增强点
    Advisor advisor = new DefaultPointcutAdvisor(cba);
    pf.addAdvice(nop);
    pf.addAdvisor(advisor);
    //获取代理对象
    ITestBean proxied = (ITestBean) pf.getProxy();
    //方法调用
    proxied.setAge(5);
    assertEquals(1, cba.getCalls());
    assertEquals(1, nop.getCount());
    assertTrue(pf.removeAdvisor(advisor));
    assertEquals(5, proxied.getAge());
    assertEquals(1, cba.getCalls());
    assertEquals(2, nop.getCount());
    assertFalse(pf.removeAdvisor(new DefaultPointcutAdvisor(null)));
}

ProxFactory源码分析


public class ProxyFactory extends ProxyCreatorSupport {
}
getProxy()方法分析

获取代理的对象

public Object getProxy() {
    return createAopProxy().getProxy();
}
createAopProxy()方法实现
protected final synchronized AopProxy createAopProxy() {
    //首次创建代理时进行激活。并调用相应的拦截器
    if (!this.active) {
        activate();
    }
    return getAopProxyFactory().createAopProxy(this);
}
/**创建代理*/
@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
    if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
        Class<?> targetClass = config.getTargetClass();
        if (targetClass == null) {
            throw new AopConfigException("TargetSource cannot determine target class: " +
                    "Either an interface or a target is required for proxy creation.");
        }
        //如果被代理的类是一个接口。或者被代理的类的类型是Proxy类
        if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
            //使用jdk代理
            return new JdkDynamicAopProxy(config);
        }
        //否则使用cglib代理
        return new ObjenesisCglibAopProxy(config);
    }
    else {
        return new JdkDynamicAopProxy(config);
    }
}

具体看JdkDynamicAopProxy源码实现:
https://blog.csdn.net/ai_xiangjuan/article/details/79945536

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值