一文搞懂Spring循環(huán)依賴的原理
簡(jiǎn)介
說明
本文用實(shí)例來介紹@Autowired解決循環(huán)依賴的原理。@Autowired是通過三級(jí)緩存來解決循環(huán)依賴的。
除了@Autoired,還有其他方案來解決循環(huán)依賴的,見:Spring循環(huán)依賴的解決方案詳解
概述
@Autowired進(jìn)行屬性注入可以解決循環(huán)依賴。原理是:Spring控制了bean的生命周期,先實(shí)例化bean,后注入bean的屬性。Spring中記錄了正在創(chuàng)建中的bean(已經(jīng)實(shí)例化但還沒初始化完畢的bean),所以可以在注入屬性時(shí),從記錄的bean中取依賴的對(duì)象。
相對(duì)而言,單純使用構(gòu)造器注入就無法解決循環(huán)依賴。因?yàn)?,在?gòu)造時(shí)就需要傳入依賴的對(duì)象,導(dǎo)致無法實(shí)例化。(注意:構(gòu)造器注入可以使用@Lazy解決循環(huán)依賴,在實(shí)例化時(shí),傳入代理對(duì)象,真正使用時(shí)才會(huì)生成真正的對(duì)象)
循環(huán)依賴實(shí)例
代碼
package com.example.tmp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class A {
@Autowired
private B b;
private String name = "Tony";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTest() {
return b.getAge().toString() + name;
}
}
package com.example.tmp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class B {
@Autowired
private A a;
private Integer age = 20;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
package com.example.controller;
import com.example.tmp.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Autowired
private A a;
@GetMapping("/test1")
public String test1() {
return a.getTest();
}
}
測(cè)試
1.啟動(dòng)不報(bào)錯(cuò)。
2.postman訪問:http://localhost:8080/test1
后端結(jié)果:不報(bào)錯(cuò)
postman結(jié)果: 20Tony
到此這篇關(guān)于一文搞懂Spring循環(huán)依賴的原理的文章就介紹到這了,更多相關(guān)Spring循環(huán)依賴內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解如何在Spring Boot中實(shí)現(xiàn)容錯(cuò)機(jī)制
容錯(cuò)機(jī)制是構(gòu)建健壯和可靠的應(yīng)用程序的重要組成部分,它可以幫助應(yīng)用程序在面對(duì)異?;蚬收蠒r(shí)保持穩(wěn)定運(yùn)行,Spring Boot提供了多種機(jī)制來實(shí)現(xiàn)容錯(cuò),包括異常處理、斷路器、重試和降級(jí)等,本文將介紹如何在Spring Boot中實(shí)現(xiàn)這些容錯(cuò)機(jī)制,需要的朋友可以參考下2023-10-10
Lombok注解之@SuperBuilder--解決無法builder父類屬性問題
這篇文章主要介紹了Lombok注解之@SuperBuilder--解決無法builder父類屬性問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
Spring Cloud OAuth2中/oauth/token的返回內(nèi)容格式
Spring Cloud OAuth2 生成access token的請(qǐng)求/oauth/token的返回內(nèi)容就需要自定義,本文就詳細(xì)介紹一下,感興趣的可以了解一下2021-07-07
SpringBoot使用自定義注解實(shí)現(xiàn)權(quán)限攔截的示例
本篇文章主要介紹了SpringBoot使用自定義注解實(shí)現(xiàn)權(quán)限攔截的示例,具有一定的參考價(jià)值,有興趣的可以了解一下2017-09-09
maven打包本地jar到項(xiàng)目中的方法實(shí)現(xiàn)
本文主要介紹了maven打包本地jar到項(xiàng)目中的方法實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06

