Java程序員自動組件注入的幾種方式你會哪一種?
創(chuàng)新互聯(lián)公司主要從事做網(wǎng)站、網(wǎng)站設(shè)計、網(wǎng)頁設(shè)計、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)湯陰,十載網(wǎng)站建設(shè)經(jīng)驗,價格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):13518219792
Java程序員在開發(fā)的時候,一般都會遇到組件注入這個問題,回想起當(dāng)年剛進入Java程序員這個行業(yè)的時候也遇到過這樣的問題,那么我們今天就來討論一下組件注入會有哪幾種方式,希望能幫助大家快速攻破這個技術(shù)難點。
注入依賴對象可以采用手工裝配或自動裝配,在實際應(yīng)用中建議使用手工裝配,因為自動裝配會產(chǎn)生未知情況,開發(fā)人員無法預(yù)見最終的裝配結(jié)果。
問題1:@Autowired 、@Inject 、@Resource 的區(qū)別
@Autowired
[if !supportLists]· [endif]Spring標(biāo)準(zhǔn)
[if !supportLists]· [endif]按照類型注入(ByType)
[if !supportLists]· [endif]AutowiredAnnotationBeanPostProcessor對其進行處理
[if !supportLists]· [endif]支持屬性、set方法、構(gòu)造方法注入,可以聯(lián)合@Qualifier完成ByName,聯(lián)合@Primary解決同類多 Bean沖突(不推薦,除非迫不得已)
[if !supportLists]· [endif]擁有required屬性判定空
[if !supportLists]· [endif]構(gòu)造函數(shù)只能有一個,構(gòu)造方法注入@Autowire可以不帶
[if !supportLists]· [endif]@Configuration中也可以不帶@Autowire
[if !supportLists]· [endif]推薦set方法、構(gòu)造方法注入
@Resource
[if !supportLists]· [endif]JSR250標(biāo)準(zhǔn)
[if !supportLists]· [endif]按照名稱注入(ByName)
[if !supportLists]· [endif]CommonAnnotationBeanPostProcessor對其進行處理
[if !supportLists]· [endif]不支持@Qualifier、@Primary
[if !supportLists]· [endif]不支持required屬性判定空
@Inject
[if !supportLists]· [endif]JSR330
[if !supportLists]· [endif]按照名稱注入(ByType)
[if !supportLists]· [endif]支持@Qualifier、@Primary
[if !supportLists]· [endif]不支持required屬性判定空
[if !supportLists]· [endif]需要依賴
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
問題2:下面代碼有沒有問題?
@Configuration
public class WorkerConfiguration {
@Autowired
Environment environment;
public WorkerConfiguration(){
System.out.println(environment.getProperty("os.name"));
}
@Bean
public Dept dept() {
System.out.println("dept>>>>>>>>>>>>>>>>>>>");
return new Dept();
}
}
當(dāng)前文章:Java程序員自動組件注入的幾種方式你會哪一種?
當(dāng)前URL:http://bm7419.com/article46/jddphg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供商城網(wǎng)站、動態(tài)網(wǎng)站、自適應(yīng)網(wǎng)站、靜態(tài)網(wǎng)站、營銷型網(wǎng)站建設(shè)、定制網(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)