最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

一文搞懂Spring循環(huán)依賴的原理

 更新時(shí)間:2022年07月09日 09:52:46   作者:IT利刃出鞘  
這篇文章將用實(shí)例來為大家詳細(xì)介紹@Autowired解決循環(huán)依賴的原理,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Spring有一定幫助,感興趣的可以學(xué)習(xí)一下

簡(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)文章

最新評(píng)論

滦平县| 青阳县| 琼中| 高阳县| 大城县| 通化市| 天台县| 如皋市| 页游| 阳山县| 宽甸| 江城| 和顺县| 大宁县| 织金县| 大同市| 梁山县| 行唐县| 朝阳区| 高陵县| 广饶县| 武夷山市| 疏附县| 九龙坡区| 琼中| 晋江市| 鹤庆县| 招远市| 白城市| 宜都市| 华安县| 灵宝市| 临颍县| 长子县| 丹巴县| 桐乡市| 洛浦县| 秀山| 台中县| 东宁县| 贡嘎县|