Spring源码解析
办公设备租赁,深圳惠源.
一、ProxyFactory
Spring通过ProxyFactory创建代理对象,可以看Spring源码解析(三)
public Object getProxy() {
return createAopProxy().getProxy();
}
protected final synchronized AopProxy createAopProxy() {
if (!this.active) {
activate();
}
return getAopProxyFactory().createAopProxy(this);
}
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.");
}
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
return new ObjenesisCglibAopProxy(config);
}
else {
return new JdkDynamicAopProxy(config);
}
从以上可以看出一般情况下使用jdk代理,除非设置了proxyTargetClass为true或者没有实现接口,所有我们主要看下proxyTargetClass在那个位置设置
获取注解属性proxyTargetClass为true的时候执行AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry),而proxyTargetClass是@EnableTransactionManagement的属性
AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry)
public static final String AUTO_PROXY_CREATOR_BEAN_NAME =
"org.springframework.aop.config.internalAutoProxyCreator";
public static void forceAutoProxyCreatorToUseClassProxying(BeanDefinitionRegistry registry) {
if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
BeanDefinition definition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
definition.getPropertyValues().add("proxyTargetClass", Boolean.TRUE);
}
}
从forceAutoProxyCreatorToUseClassProxying点击引用,看到AopAutoConfig也调用了该方法
ClassProxyingConfiguration
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingClass("org.aspectj.weaver.Advice")
@ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true",
matchIfMissing = true)
static class ClassProxyingConfiguration {
ClassProxyingConfiguration(BeanFactory beanFactory) {
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
}
}
}
总结
当设置@EnableTransactionManagement的proxyTargetClass=true,或者spring.aop.proxy-target-class为true的时候使用cglib代理 [办公设备租赁,深圳惠源](https://www.huiyuan136.com/).