一文搞懂Spring循環(huán)依賴的原理
簡介
說明
本文用實例來介紹@Autowired解決循環(huán)依賴的原理。@Autowired是通過三級緩存來解決循環(huán)依賴的。
除了@Autoired,還有其他方案來解決循環(huán)依賴的,見:Spring循環(huán)依賴的解決方案詳解
概述
@Autowired進行屬性注入可以解決循環(huán)依賴。原理是:Spring控制了bean的生命周期,先實例化bean,后注入bean的屬性。Spring中記錄了正在創(chuàng)建中的bean(已經(jīng)實例化但還沒初始化完畢的bean),所以可以在注入屬性時,從記錄的bean中取依賴的對象。
相對而言,單純使用構(gòu)造器注入就無法解決循環(huán)依賴。因為,在構(gòu)造時就需要傳入依賴的對象,導(dǎo)致無法實例化。(注意:構(gòu)造器注入可以使用@Lazy解決循環(huán)依賴,在實例化時,傳入代理對象,真正使用時才會生成真正的對象)
循環(huán)依賴實例
代碼
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(); } }
測試
1.啟動不報錯。
2.postman訪問:http://localhost:8080/test1
后端結(jié)果:不報錯
postman結(jié)果: 20Tony
到此這篇關(guān)于一文搞懂Spring循環(huán)依賴的原理的文章就介紹到這了,更多相關(guān)Spring循環(huán)依賴內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Lombok注解之@SuperBuilder--解決無法builder父類屬性問題
這篇文章主要介紹了Lombok注解之@SuperBuilder--解決無法builder父類屬性問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09Spring Cloud OAuth2中/oauth/token的返回內(nèi)容格式
Spring Cloud OAuth2 生成access token的請求/oauth/token的返回內(nèi)容就需要自定義,本文就詳細介紹一下,感興趣的可以了解一下2021-07-07SpringBoot使用自定義注解實現(xiàn)權(quán)限攔截的示例
本篇文章主要介紹了SpringBoot使用自定義注解實現(xiàn)權(quán)限攔截的示例,具有一定的參考價值,有興趣的可以了解一下2017-09-09