环球ug开户:Spring若何解决循环依赖?

admin 3个月前 (06-23) 科技 39 0

先容

先说一下什么是循环依赖,Spring在初始化A的时刻需要注入B,而初始化B的时刻需要注入A,在Spring启动后这2个Bean都要被初始化完成

Spring的循环依赖有两种场景

  1. 组织器的循环依赖
  2. 属性的循环依赖

组织器的循环依赖,可以在组织函数中使用@Lazy注解延迟加载。在注入依赖时,先注入署理工具,当首次使用时再建立工具完成注入

属性的循环依赖主要是通过3个map来解决的

组织器的循环依赖

@Component
public class ConstructorA {

	private ConstructorB constructorB;

	@Autowired
	public ConstructorA(ConstructorB constructorB) {
		this.constructorB = constructorB;
	}
}
@Component
public class ConstructorB {

	private ConstructorA constructorA;

	@Autowired
	public ConstructorB(ConstructorA constructorA) {
		this.constructorA = constructorA;
	}
}
@Configuration
@ComponentScan("com.javashitang.dependency.constructor")
public class ConstructorConfig {
}
public class ConstructorMain {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext context =
				new AnnotationConfigApplicationContext(ConstructorConfig.class);
		System.out.println(context.getBean(ConstructorA.class));
		System.out.println(context.getBean(ConstructorB.class));
	}
}

运行ConstructorMain的main方式的时刻会在第一行就报异常,说明Spring没办法初始化所有的Bean,即上面这种形式的循环依赖Spring无法解决。

我们可以在ConstructorA或者ConstructorB组织函数的参数上加上@Lazy注解就可以解决

@Autowired
public ConstructorB(@Lazy ConstructorA constructorA) {
	this.constructorA = constructorA;
}

由于我们主要关注属性的循环依赖,组织器的循环依赖就不做过多剖析了

属性的循环依赖

先演示一下什么是属性的循环依赖

@Component
public class FieldA {

	@Autowired
	private FieldB fieldB;
}
@Component
public class FieldB {

	@Autowired
	private FieldA fieldA;
}
@Configuration
@ComponentScan("com.javashitang.dependency.field")
public class FieldConfig {
}
public class FieldMain {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext context =
				new AnnotationConfigApplicationContext(FieldConfig.class);
		// com.javashitang.dependency.field.FieldA@3aa9e816
		System.out.println(context.getBean(FieldA.class));
		// com.javashitang.dependency.field.FieldB@17d99928
		System.out.println(context.getBean(FieldB.class));
	}
}

Spring容器正常启动,能获取到FieldA和FieldB这2个Bean

属性的循环依赖在面试中照样经常被问到的。总体来说也不庞大,然则涉及到Spring Bean的初始化历程,以是感受对照庞大,我写个demo演示一下整个历程

Spring的Bean的初始化历程实在对照庞大,为了利便明了Demo,我就把Spring Bean的初始化历程分为2部门

  1. bean的实例化历程,即挪用组织函数将工具建立出来
  2. bean的初始化历程,即填充bean的种种属性

bean初始化历程完毕,则bean就能被正常建立出来了

下面最先写Demo,ObjectFactory接口用来生产Bean,和Spring中界说的接口一样

public interface ObjectFactory<T> {
	T getObject();
}
public class DependencyDemo {

	// 初始化完毕的Bean
	private final Map<String, Object> singletonObjects =
			new ConcurrentHashMap<>(256);

	// 正在初始化的Bean对应的工厂,此时工具已经被实例化
	private final Map<String, ObjectFactory<?>> singletonFactories =
			new HashMap<>(16);

	// 存放正在初始化的Bean,工具还没有被实例化之前就放进来了
	private final Set<String> singletonsCurrentlyInCreation =
			Collections.newSetFromMap(new ConcurrentHashMap<>(16));

	public  <T> T getBean(Class<T> beanClass) throws Exception {
		// 类名为Bean的名字
		String beanName = beanClass.getSimpleName();
		// 已经初始化好了,或者正在初始化
		Object initObj = getSingleton(beanName, true);
		if (initObj != null) {
			return (T) initObj;
		}
		// bean正在被初始化
		singletonsCurrentlyInCreation.add(beanName);
		// 实例化bean
		Object object = beanClass.getDeclaredConstructor().newInstance();
		singletonFactories.put(beanName, () -> {
			return object;
		});
		// 最先初始化bean,即填充属性
		Field[] fields = object.getClass().getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			// 获取需要注入字段的class
			Class<?> fieldClass = field.getType();
			field.set(object, getBean(fieldClass));
		}
		// 初始化完毕
		singletonObjects.put(beanName, object);
		singletonsCurrentlyInCreation.remove(beanName);
		return (T) object;
	}

	/**
	 * allowEarlyReference参数的寄义是Spring是否允许循环依赖,默以为true
	 * 以是当allowEarlyReference设置为false的时刻,当项目存在循环依赖,会启动失败
	 */
	public Object getSingleton(String beanName, boolean allowEarlyReference) {
		Object singletonObject = this.singletonObjects.get(beanName);
		if (singletonObject == null 
				&& isSingletonCurrentlyInCreation(beanName)) {
			synchronized (this.singletonObjects) {
				if (singletonObject == null && allowEarlyReference) {
					ObjectFactory<?> singletonFactory =
							this.singletonFactories.get(beanName);
					if (singletonFactory != null) {
						singletonObject = singletonFactory.getObject();
					}
				}
			}
		}
		return singletonObject;
	}

	/**
	 * 判断bean是否正在被初始化
	 */
	public boolean isSingletonCurrentlyInCreation(String beanName) {
		return this.singletonsCurrentlyInCreation.contains(beanName);
	}

}

测试一波

public static void main(String[] args) throws Exception {
	DependencyDemo dependencyDemo = new DependencyDemo();
	// 冒充扫描出来的工具
	Class[] classes = {A.class, B.class};
	// 冒充项目初始化所有bean
	for (Class aClass : classes) {
		dependencyDemo.getBean(aClass);
	}
	// true
	System.out.println(
			dependencyDemo.getBean(B.class).getA() == dependencyDemo.getBean(A.class));
	// true
	System.out.println(
			dependencyDemo.getBean(A.class).getB() == dependencyDemo.getBean(B.class));
}

是不是很简朴?我们只用了2个map就搞定了Spring的循环依赖

2个Map就能搞定循环依赖,那为什么Spring要用3个Map呢?

缘故原由实在也很简朴,当我们从singletonFactories中凭据BeanName获取响应的ObjectFactory,然后挪用getObject()这个方式返回对应的Bean。在我们的例子中
ObjectFactory的实现很简朴哈,就是将实例化好的工具直接返回,然则在Spring中就没有这么简朴了,执行历程对照庞大,为了制止每次拿到ObjectFactory然后挪用getObject(),我们直接把ObjectFactory建立的工具缓存起来不就行了,这样就能提高效率了

好比A依赖B和C,B和C又依赖A,若是不做缓存那么初始化B和C都市挪用A对应的ObjectFactory的getObject()方式。若是做缓存只需要B或者C挪用一次即可。

知道了思绪,我们把上面的代码改一波,加个缓存。

public class DependencyDemo {

	// 初始化完毕的Bean
	private final Map<String, Object> singletonObjects =
			new ConcurrentHashMap<>(256);

	// 正在初始化的Bean对应的工厂,此时工具已经被实例化
	private final Map<String, ObjectFactory<?>> singletonFactories =
			new HashMap<>(16);

	// 缓存Bean对应的工厂生产好的Bean
	private final Map<String, Object> earlySingletonObjects =
			new HashMap<>(16);

	// 存放正在初始化的Bean,工具还没有被实例化之前就放进来了
	private final Set<String> singletonsCurrentlyInCreation =
			Collections.newSetFromMap(new ConcurrentHashMap<>(16));

	public  <T> T getBean(Class<T> beanClass) throws Exception {
		// 类名为Bean的名字
		String beanName = beanClass.getSimpleName();
		// 已经初始化好了,或者正在初始化
		Object initObj = getSingleton(beanName, true);
		if (initObj != null) {
			return (T) initObj;
		}
		// bean正在被初始化
		singletonsCurrentlyInCreation.add(beanName);
		// 实例化bean
		Object object = beanClass.getDeclaredConstructor().newInstance();
		singletonFactories.put(beanName, () -> {
			return object;
		});
		// 最先初始化bean,即填充属性
		Field[] fields = object.getClass().getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			// 获取需要注入字段的class
			Class<?> fieldClass = field.getType();
			field.set(object, getBean(fieldClass));
		}
		singletonObjects.put(beanName, object);
		singletonsCurrentlyInCreation.remove(beanName);
		earlySingletonObjects.remove(beanName);
		return (T) object;
	}

	/**
	 * allowEarlyReference参数的寄义是Spring是否允许循环依赖,默以为true
	 */
	public Object getSingleton(String beanName, boolean allowEarlyReference) {
		Object singletonObject = this.singletonObjects.get(beanName);
		if (singletonObject == null
				&& isSingletonCurrentlyInCreation(beanName)) {
			synchronized (this.singletonObjects) {
				singletonObject = this.earlySingletonObjects.get(beanName);
				if (singletonObject == null && allowEarlyReference) {
					ObjectFactory<?> singletonFactory =
							this.singletonFactories.get(beanName);
					if (singletonFactory != null) {
						singletonObject = singletonFactory.getObject();
						this.earlySingletonObjects.put(beanName, singletonObject);
						this.singletonFactories.remove(beanName);
					}
				}
			}
		}
		return singletonObject;
	}
}

我们写的getSingleton的实现和org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton(java.lang.String, boolean)的实现一模一样,这个方式险些所有剖析Spring循环依赖的文章都市提到,这次你明了事情原理是什么了把

总结一波

  1. 拿bean的时刻先从singletonObjects(一级缓存)中获取
  2. 若是获取不到,而且工具正在建立中,就从earlySingletonObjects(二级缓存)中获取
  3. 若是照样获取不到就从singletonFactories(三级缓存)中获取,然后将获取到的工具放到earlySingletonObjects(二级缓存)中,而且将bean对应的singletonFactories(三级缓存)消灭
  4. bean初始化完毕,放到singletonObjects(一级缓存)中,将bean对应的earlySingletonObjects(二级缓存)消灭

迎接关注

参考博客

[1]https://mp.weixin.qq.com/s/gBr3UfC1HRcw4U-ZMmtRaQ
[2]https://mp.weixin.qq.com/s/5mwkgJB7GyLdKDgzijyvXw
对照详细
[1]https://zhuanlan.zhihu.com/p/84267654
[2]https://juejin.im/post/5c98a7b4f265da60ee12e9b2

,

欧博allbet网址

欢迎进入欧博allbet网址(Allbet Game):www.aLLbetgame.us,欧博官网是欧博集团的官方网站。欧博官网开放Allbet注册、Allbe代理、Allbet电脑客户端、Allbet手机版下载等业务。

Allbet声明:该文看法仅代表作者自己,与本平台无关。转载请注明:环球ug开户:Spring若何解决循环依赖?

网友评论

  • (*)

最新评论

文章归档

站点信息

  • 文章总数:668
  • 页面总数:0
  • 分类总数:8
  • 标签总数:1076
  • 评论总数:245
  • 浏览总数:14718