本文研究的主要是Spring bean 加載執(zhí)行順序的相關(guān)內(nèi)容,具體如下。

問題來源:
有一個bean為A,一個bean為B。想要A在容器實例化的時候的一個屬性name賦值為B的一個方法funB的返回值。
如果只是在A里單純的寫著:
private B b;
private String name = b.funb();
會報錯說nullpointException,因為這個時候b還沒被set進來,所以為null。
解決辦法為如下代碼,同時學(xué)習(xí)下spring中 InitializingBean ,對象構(gòu)造方法 , init-method 的執(zhí)行順序。
public class A implements InitializingBean {
private B b;
private String name;
// = b.funb();
public void setB(B b) {
System.out.println("A.setB initialed");
this.b = b;
}
public A() {
System.out.println("A initialed");
}
public void init() {
System.out.println("init");
this.name = b.funb();
}
@Override
public String toString() {
return super.toString() + this.name;
}
public void afterPropertiesSet() throws Exception {
//其實放在這里也可以
//this.name = b.funb();
System.out.println("afterPropertiesSet");
}
}
public class B {
public String funb() {
System.out.println("funb");
return "B.funb";
}
public B() {
System.out.println("B initialed");
}
}
文章標(biāo)題:Springbean加載執(zhí)行順序?qū)嵗馕?創(chuàng)新互聯(lián)
網(wǎng)頁路徑:http://chinadenli.net/article34/dsjise.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站設(shè)計、網(wǎng)站制作、自適應(yīng)網(wǎng)站、移動網(wǎng)站建設(shè)、標(biāo)簽優(yōu)化、網(wǎng)站排名
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容