【Spring】使用一级缓存模拟Spring解决循环依赖问题

使用一级缓存模拟Spring解决循环依赖

代码

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 模拟使用一级缓存来解决Spring中的循环依赖问题
 */
public class Main {

    //用来存放半成品对象的缓存
    private static Map<String, Object> cache = new HashMap<>();

    private static Object getBean(Class<?> clazz) throws InstantiationException, IllegalAccessException {
        String beanName = clazz.getName().toLowerCase();

        if (cache.containsKey(beanName)) {
            return cache.get(beanName);
        }

        //创建半成品对象后直接放入缓存
        Object bean = clazz.newInstance();
        cache.put(beanName, bean);

        //对半成品对象进行属性填充
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            Class<?> type = field.getType();
            field.setAccessible(true);
            String fieldBeanName = type.getName().toLowerCase();
            Object fieldInstance = null;
            //优先从缓存中获取半成品对象
            if (cache.containsKey(fieldBeanName)) {
                fieldInstance = cache.get(fieldBeanName);
            } else {
                fieldInstance = getBean(type);
            }

            field.set(bean, fieldInstance);
            field.setAccessible(false);
        }
        return bean;
    }

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        System.out.println(((A)Main.getBean(A.class)).b);
        System.out.println(((B)Main.getBean(B.class)).a);
    }

}

class A {
    B b;
}

class B {
    A a;
}

循环依赖

posted @ 2021-12-13 13:38  herrhu  阅读(196)  评论(0编辑  收藏  举报