關(guān)于@Autowired使用的幾點(diǎn)建議

建議一:

優(yōu)先選擇@Autowired注入,而不是@Resource
注入原理:@Autowired會(huì)先按類型注入,然后按照名稱注入,都無法找到唯一的一個(gè)實(shí)現(xiàn)類則報(bào)錯(cuò)。這于@Resource相反

建議二:

@Autowired最好與@Qualifier()一起使用,不要圖省事,雖然大多數(shù)情況下只用@Autowired就可以正常注入

建議三:

@Autowired可以用在字段或者setter方法上或者構(gòu)造器上。
但是不推薦用在字段上,容易發(fā)生空指針錯(cuò)誤,推薦使用在構(gòu)造器或者setter方法上,如下:

  1. 使用字段注入容易發(fā)生空指針異常
    下面的代碼只做演示,實(shí)際開發(fā)中不會(huì)這樣寫
@RestController
public class PersonController {
    @Autowired
    @Qualifier("personService")
    private PersonService personService;
    private String name;

    // 構(gòu)造方法
    public PersonController() {
        this.name = personService.getName(); // 這里會(huì)報(bào)空指針異常
    }
}

原因是構(gòu)造方法先于@Autowired被初始化。
PS:Java變量的初始化順序?yàn)椋?/strong>靜態(tài)變量或靜態(tài)語句塊 –> 實(shí)例變量或初始化語句塊 –> 構(gòu)造方法 –> @Autowired

  1. 在構(gòu)造器上使用:
    優(yōu)點(diǎn):
    ①可以防止上面所說的空指針異常
    ②可以明確成員變量的加載順序
    下面是官方推薦的寫法:
@RestController
public class PersonController {

    private final PersonService personService;

   /**
     * Spring Team建議:“始終在bean中使用基于構(gòu)造函數(shù)的依賴注入。始終使用斷言來強(qiáng)制依賴”。
     */
    @Autowired
    public PersonController(@Qualifier("personService") PersonService personService){
        Assert.notNull(personService, "personService must not be null");
        this.personService = personService;
    }
}
  1. 在setter方法上使用
@RestController
public class PersonController {

    private PersonService personService;

    @Autowired
    @Qualifier("personService")
    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容