O cache de terceiro nível resolve a dependência circular no processo de criação de beans
1. O que é uma dependência circular?
Ou seja, A depende de B, B depende de C e C depende de A. Tais problemas fazem com que A nunca seja concluído quando instanciado.
Classificação das dependências circulares:
-
Dependência Circular Construtora
Esta situação não pode ser resolvida. Como ele deve ser instanciado por meio do construtor, é impossível não chamar o construtor e é impossível evitar a ocorrência de dependências. Lançado neste momento
BeanCurrentlyInCreationException
. -
setter dependências circulares. Beans que já foram instanciados podem ser expostos antecipadamente separando instanciação e inicialização.
O Spring só pode resolver o problema de dependência circular de beans singleton no caso de setters:
/** Cache of singleton objects: bean name --> bean instance */ //一级缓存,存放成品对象
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Cache of singleton factories: bean name --> ObjectFactory *///三级缓存,存放函数式接口,完成代理对象的覆盖
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
/** Cache of early singleton objects: bean name --> bean instance *///二级缓存,存放半成品对象
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
private final Set<String> registeredSingletons = new LinkedHashSet<>(256); //已经创建成功的单例
2. Análise de dependências circulares
Acompanhamos o processo de execução do programa para analisar como o spring resolve dependências circulares.
Sabemos que no processo de carregamento do arquivo de configuração da mola, o método de atualização será acionado. específico:
AbstractBeanFactory#refresh()#finishBeanFactoryInitialization(beanFactory)
em , vai passar
getBean(beanName)
O método conclui a criação do objeto. Aqui está a chamada doGetBean
, que primeiro chamará o getSingleton(beanName)
método :
//getSingleton(beanName) 调用的实际方法
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
//首先从一级缓存 singletonObjects 中获取成品对象
Object singletonObject = this.singletonObjects.get(beanName);
//一级缓存为 null 且 bean 正在创建(循环依赖发生了,则触发二级缓存)
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;
}
Não há objeto para a primeira criação e null é retornado diretamente. Neste ponto, o bean é criado através getSingleton
do :
getSingleton
O método de parâmetro de interface: o parâmetro de interface aqui é nosso cache L3. Neste momento, não há cache L3, então crie-o createBean
criando . Neste método será chamado
// Create bean instance.
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
//多例的处理逻辑,直接 createBean
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
getSingleton
O método de parâmetro de interface: o parâmetro de interface aqui é nosso cache L3. Neste momento, não há cache L3, então crie-o createBean
criando .
Pense em por que o cache de terceiro nível armazena métodos de interface, um é que usamos essa propriedade para criar beans e o outro é um aprimoramento.
Então ele pode criar um bean com sucesso e, se o bean for dependente, pode realizar a operação de criação do bean proxy por meio de getEarlyBeanReference. Este processo substitui o bean criado por um bean proxy.
//通过 ObjectFactory 获取实例
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
//一级缓存中获取
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
beforeSingletonCreation(beanName);//标记创建中
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
//从三级缓存中获取,此时三级缓存不存在,所以会去创建一个
//此时会回调到 createBean#doCreateBean#createBeanInstance
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
//.....
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
afterSingletonCreation(beanName);
}
if (newSingleton) {
//触发创建操作后,此处执行三级缓存机制(将 B 加入)
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
Anexo: mecanismo de cache de três níveis:
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, singletonObject); //加入一级缓存
this.singletonFactories.remove(beanName); //移除三级缓存
this.earlySingletonObjects.remove(beanName); //移除二级缓存
this.registeredSingletons.add(beanName); //标记已创建
}
}
Uma dependência circular ocorre durante a atribuição de propriedade após a criação do bean. Por exemplo, no processo de criação de A, você precisa ir para a instância B. Se B não existir, você precisa criar B. Depois de criar B, você precisa criar A para atribuição de atributo. Neste momento, quando B cria A, ele primeiro irá para o cache de segundo nível para obter o A semi-acabado, pulando assim a segunda instância de A. Depois que B obtém o produto semi-acabado A, ele conclui a criação. Ou seja, existe a em B, e b em a é nulo, porque A ainda é um produto semi-acabado e ainda não há atribuição de atributos.
Quando B é criado, A é criado.
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
//earlySingletonExposure 只有当支持循环依赖,才使用三级缓存,解决代理问题
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper); //填充属性,循环依赖发生
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
//....
if (earlySingletonExposure) {
//尝试从缓冲中获取
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
//这里需要说明的是,getEarlyBeanReference 是一个实现 aop 的增强方法,代理对象
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
//如果存在 BeanPostProcessors,需要代理,则生成代理对象
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
//拿到代理 bean 并覆盖,SmartInstantiationAwareBeanPostProcessor 会在实例化过程中进行增强操作
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
return exposedObject;
}
//轮询初始化 bean,但此时 bean 尚未实例化要知道
// Trigger initialization of all non-lazy singleton beans...
下一步轮询 bean,是否实现了 SmartInitializingSingleton 的增强操作
// Trigger post-initialization callback for all applicable beans...
Resumir
Para resolver o problema de dependência circular, o cache de segundo nível pode ser implementado.
O uso do cache L3 pode resolver o problema dos beans proxy.
Desde que a interface Aware esteja implementada e seu método setxxxAware seja reescrito, suas propriedades podem ser obtidas através do objeto.
Retirada de proxy dinâmico: aprimoramento de interceptação @lookup