一、AOP执行顺序
Spring4和Spring5的执行顺序:
二、循环依赖
构造器注入无法解决循环依赖。
以set方式注入依赖。
三、spring的三级缓存
解决spring循环依赖----spring的三级缓存。
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
/** Maximum number of suppressed exceptions to preserve. */
private static final int SUPPRESSED_EXCEPTIONS_LIMIT = 100;
/** Cache of singleton objects: bean name to bean instance. */
// 一级缓存 成品bean 经历了完整的生命周期的bean
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Cache of singleton factories: bean name to ObjectFactory. */
// 三级缓存 用来构建bean的工厂
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
/** Cache of early singleton objects: bean name to bean instance. */
// 二级缓存 半成品bean 实例化,但未初始化的bean
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);
/** Set of registered singletons, containing the bean names in registration order. */
private final Set<String> registeredSingletons = new LinkedHashSet<>(256);
/** Names of beans that are currently in creation. */
private final Set<String> singletonsCurrentlyInCreation =
Collections.newSetFromMap(new ConcurrentHashMap<>(16));
/** Names of beans currently excluded from in creation checks. */
private final Set<String> inCreationCheckExclusions =
Collections.newSetFromMap(new ConcurrentHashMap<>(16));
实例化:申请一块空间。
初始化:属性赋值。
A先实例化---》放入三级缓存
A初始化---》需要B,三级缓存中没有B
---》实例化B,放三级缓存,
---》初始化B,需要A,从一级缓存找,没有,二级缓存找,没有,三级
缓存找,有---》将A放入二级缓存,删掉三级缓存中的A
---》给B中a属性赋值,B创建完成,放入一级缓存
---》从一级缓存中拿到B,给A中得b赋值,将A放到一级缓存,删除二级缓存中得A