第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在Spring App中調(diào)用未使用的Bean

在Spring App中調(diào)用未使用的Bean

慕哥6287543 2021-04-15 22:23:09
我的Spring應(yīng)用程序中有一些奇怪的行為,這是Java Spring Boot應(yīng)用程序的結(jié)構(gòu):在包裝中com.somethingsomething.packageA,我有2個文件首先是ParentA.javapackage com.somethingsomething.packageA;import javax.annotation.PostConstruct;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;@Componentpublic class ParentA {    @Autowired    private ChildA childA;    public ChildA getChildA() {        return childA;    }    @PostConstruct    public void ParentAPostConstruct() {        System.out.println("ParentA PostConstruct were called");    }}第二個是ChildA.javapackage com.somethingsomething.packageA;import org.springframework.stereotype.Component;@Componentpublic class ChildA {    public ChildA() {        System.out.println("ChildA were called");    }}然后在package下com.somethingsomething.packageB,我也有兩個類似的文件。首先是ParentB.javapackage com.somethingsomething.packageB;import javax.annotation.PostConstruct;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;@Componentpublic class ParentB {    @Autowired    private ChildB childB;    public ChildB getChildB() {        return childB;    }    @PostConstruct    public void ParentBPostConstruct() {        System.out.println("ParentB PostConstruct were called");    }}第二個是ChildB.javapackage com.somethingsomething.packageB;import org.springframework.stereotype.Component;@Componentpublic class ChildB {    public ChildB() {        System.out.println("ChildB were called");    }}但是在這種情況下ChildA were called并ParentA PostConstruct were called沒有被假設(shè)要記錄。那么,為什么會發(fā)生這種特殊的行為呢?這是Spring的默認(rèn)行為嗎?
查看完整描述

3 回答

?
互換的青春

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個贊

是的,這是Spring的默認(rèn)行為。在應(yīng)用程序啟動時@Component,無論是否使用它們,都將創(chuàng)建帶有注釋的所有Bean 。

applicationContext.getBean(ParentB.class)然后,該調(diào)用僅返回已創(chuàng)建的Bean。

要回答您的編輯: 默認(rèn)情況下,Spring Bean是Singletons,因此,每個總是只有一個Bean實(shí)例applicationContext。這是Control Inversion,這意味著Spring處理對象實(shí)例化,而不是您。

具有Prototype范圍的Bean可以具有多個對象實(shí)例,并且可以由您實(shí)例化。(通過致電applicationContext.getBean(ParentA.class))。這類似于做類似的事情ParentA a = new ParentA()。

我建議您閱讀此書,以更深入地了解范圍。


查看完整回答
反對 回復(fù) 2021-04-28
?
江戶川亂折騰

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超5個贊

為什么會這樣呢?

當(dāng)您啟動Spring應(yīng)用程序時,ApplicationContext將通過組件掃描您的應(yīng)用程序并在上下文中注冊所有帶Spring注釋的bean進(jìn)行初始化。這樣可以根據(jù)需要注入它們。

這是Spring的默認(rèn)行為嗎?

是的。您可以通過將組件掃描配置為僅根據(jù)需要查看指定的軟件包來更改此行為(盡管此用例很少且相差很遠(yuǎn))。


查看完整回答
反對 回復(fù) 2021-04-28
  • 3 回答
  • 0 關(guān)注
  • 217 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號