一文搞懂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(已經實例化但還沒初始化完畢的bean),所以可以在注入屬性時,從記錄的bean中取依賴的對象。
相對而言,單純使用構造器注入就無法解決循環(huán)依賴。因為,在構造時就需要傳入依賴的對象,導致無法實例化。(注意:構造器注入可以使用@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
后端結果:不報錯
postman結果: 20Tony
到此這篇關于一文搞懂Spring循環(huán)依賴的原理的文章就介紹到這了,更多相關Spring循環(huán)依賴內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java動態(tài)代理機制詳解_動力節(jié)點Java學院整理
這篇文章主要為大家詳細介紹了Java動態(tài)代理機制,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06
SpringMVC中事務是否可以加在Controller層的問題
這篇文章主要介紹了SpringMVC中事務是否可以加在Controller層的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02
springboot如何從數(shù)據(jù)庫獲取數(shù)據(jù),用echarts顯示(數(shù)據(jù)可視化)
這篇文章主要介紹了springboot如何從數(shù)據(jù)庫獲取數(shù)據(jù),用echarts顯示(數(shù)據(jù)可視化),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12
使用Spring Boot創(chuàng)建Web應用程序的示例代碼
本篇文章主要介紹了使用Spring Boot創(chuàng)建Web應用程序的示例代碼,我們將使用Spring Boot構建一個簡單的Web應用程序,并為其添加一些有用的服務,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05
fastjson對JSONObject中的指定字段重新賦值的實現(xiàn)
這篇文章主要介紹了fastjson對JSONObject中的指定字段重新賦值的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-11-11

