图解Spring解决循环依赖

来源:juejin.cn/post/6844904122160775176
前言
正文
if (isPrototypeCurrentlyInCreation(beanName)) {throw new BeanCurrentlyInCreationException(beanName);}
Spring解决循环依赖
循环依赖的本质
将指定的一些类实例为单例
类中的字段也都实例为单例
支持循环依赖
public class A {private B b;}
public class B {private A a;}
/*** 放置创建好的bean Map*/private static MapcacheMap = new HashMap<>(2); public static void main(String[] args) {// 假装扫描出来的对象Class[] classes = {A.class, B.class};// 假装项目初始化实例化所有beanfor (Class aClass : classes) {getBean(aClass);}// checkSystem.out.println(getBean(B.class).getA() == getBean(A.class));System.out.println(getBean(A.class).getB() == getBean(B.class));}private staticT getBean(Class beanClass) { // 本文用类名小写 简单代替bean的命名规则String beanName = beanClass.getSimpleName().toLowerCase();// 如果已经是一个bean,则直接返回if (cacheMap.containsKey(beanName)) {return (T) cacheMap.get(beanName);}// 将对象本身实例化Object object = beanClass.getDeclaredConstructor().newInstance();// 放入缓存cacheMap.put(beanName, object);// 把所有字段当成需要注入的bean,创建并注入到当前bean中Field[] fields = object.getClass().getDeclaredFields();for (Field field : fields) {field.setAccessible(true);// 获取需要注入字段的classClass> fieldClass = field.getType();String fieldBeanName = fieldClass.getSimpleName().toLowerCase();// 如果需要注入的bean,已经在缓存Map中,那么把缓存Map中的值注入到该field即可// 如果缓存没有 继续创建field.set(object, cacheMap.containsKey(fieldBeanName)? cacheMap.get(fieldBeanName) : getBean(fieldClass));}// 属性填充完成,返回return (T) object;}
what?问题的本质居然是two sum!
class Solution {public int[] twoSum(int[] nums, int target) {Mapmap = new HashMap<>(); for (int i = 0; i < nums.length; i++) {int complement = target - nums[i];if (map.containsKey(complement)) {return new int[] { map.get(complement), i };}map.put(nums[i], i);}throw new IllegalArgumentException("No two sum solution");}}//作者:LeetCode//链接:https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-2///来源:力扣(LeetCode)
结尾
评论





