您当前的位置: 首页 >  缓存

庄小焱

暂无认证

  • 4浏览

    0关注

    805博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Spring——spring循环依赖与三级缓存源码分析

庄小焱 发布时间:2022-04-26 22:52:05 ,浏览量:4

摘要

本博文主要是分析spring中的循环依赖的产生与spring中解决循环依赖的方案。帮助大家更好的理解spring的源码。

一、spring 循环依赖的产生

在这里插入图片描述请添加图片描述请添加图片描述

二、spring 三级缓存解决循环依赖问题

在这里插入图片描述

三、spring 三级缓存源码分析解决单例Bean

在这里插入图片描述 DefaultSingletonBeanRegistry

public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {

	/** Maximum number of suppressed exceptions to preserve. */
	private static final int SUPPRESSED_EXCEPTIONS_LIMIT = 100;

	//spring一级缓存
	/** Cache of singleton objects: bean name to bean instance. */
	private final Map singletonObjects = new ConcurrentHashMap(256);
	// spring三级缓存
	/** Cache of singleton factories: bean name to ObjectFactory. */
	private final Map singletonFactories = new HashMap(16);
	// spring二级缓存
	/** Cache of early singleton objects: bean name to bean instance. */
	private final Map earlySingletonObjects = new ConcurrentHashMap(16);
	………省略code
}
四、Spring缓存不能解决多例Bean的循环依赖问题
package com.zhuangxiaoyan.spring.srcode.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

/**
 * @Classname BService
 * @Description TODO
 * @Date 2022/5/8 15:06
 * @Created by xjl
 */
@Service
@Scope("prototype") // 多利模式
public class BService {
    @Autowired
    public AService aService;

    public AService getaService() {
        return aService;
    }

    public void setaService(AService aService){
        this.aService=aService;
    }
}
package com.zhuangxiaoyan.spring.srcode.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

/**
 * @Classname AService
 * @Description TODO
 * @Date 2022/5/8 15:06
 * @Created by xjl
 */
@Service
 @Scope("prototype")// 多利模式
public class AService {

    @Autowired
    private BService bService;

    public BService getbService() {
        return bService;
    }

    public void setbService(BService bService) {
        this.bService = bService;
    }

    public AService(){
        System.out.println("设置为无参数构造函数……");
    }
    // 为A 比B 先设置呢?

}

循环依赖异常在spring的bean的配置的单例的是时候 spring 利用的三级缓存决绝了,但是spring的bean的是多例的时候,是没有办法解决循环依赖的问题。为什么在但是时候可以采用的三级缓存来实现呢?而多例的时候不行?因为在在多利的情况下注入的bean的对象是不明确的,所以spring不知道用哪一个生产的bean的对象。 在这里插入图片描述

博文参考
关注
打赏
1657692713
查看更多评论
立即登录/注册

微信扫码登录

0.0403s