建議一:
優(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方法上,如下:
- 使用字段注入容易發(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
- 在構(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;
}
}
- 在setter方法上使用
@RestController
public class PersonController {
private PersonService personService;
@Autowired
@Qualifier("personService")
public void setPersonService(PersonService personService) {
this.personService = personService;
}
}