介绍
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