Spring自動裝配@Autowired教程
今天來跟大家聊聊簡單聊聊@Autowired,Autowired翻譯過來為自動裝配,也就是自動給Bean對象的屬性賦值。
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD,
ElementType.PARAMETER, ElementType.FIELD,
ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
/**
* Declares whether the annotated dependency is required.
* <p>Defaults to {@code true}.
*/
boolean required() default true;
}
以上是@Autowired的定義,重點(diǎn)看 @Target,我們發(fā)現(xiàn)@Autowired可以寫在:
- ElementType.CONSTRUCTOR:表示可以寫在構(gòu)造方法上
- ElementType.METHOD:表示可以寫在普通方法上
- ElementType.PARAMETER:表示可以寫在方法參數(shù)前
- ElementType.FIELD:表示可以寫在屬性上
- ElementType.ANNOTATION_TYPE:表示可以寫在其他注解上
寫在構(gòu)造方法上
對于@Autowired寫在構(gòu)造方法上的情況,跟Spring選擇構(gòu)造方法的邏輯有關(guān),一個類中是不是有多個構(gòu)造方法,是不是加了@Autowired注解,是不是有默認(rèn)構(gòu)造方法,跟構(gòu)造方法參數(shù)類型和個數(shù)都有關(guān)系,后面單獨(dú)來介紹。
寫在普通方法上
對于@Autowired寫在普通方法上的情況,我們通常寫的setter方法其實(shí)就是一個普通的setter方法,那非setter方法上加@Autowired會有作用嗎?
比如:
@Component
public class UserService {
@Autowired
public void test(OrderService orderService) {
System.out.println(orderService);
}
}這個test方法會被Spring自動調(diào)用到,并且能打印出OrderService對應(yīng)的Bean對象。
寫在方法參數(shù)前
把@Autowired寫在參數(shù)前沒有多大意義,只在spring-test中有去處理這種情況,源碼注釋原文:
Although @Autowired can technically be declared on individual method or constructor parameters since Spring Framework 5.0, most parts of the framework ignore such declarations. The only part of the core Spring Framework that actively supports autowired parameters is the JUnit Jupiter support in the spring-test module
寫在屬性上
這種情況不用多說了,值得注意的是,默認(rèn)情況下,因?yàn)锧Autowired中的required屬性為true,表示強(qiáng)制依賴,如果更加某個屬性找不到所依賴的Bean是不會賦null值的,而是會報(bào)錯,如果把required屬性設(shè)置為false,則會賦null值。
寫在其他注解上
比如我們可以自定義要給注解:
@Autowired
@Retention(RetentionPolicy.RUNTIME)
public @interface HoellerAutowired {
}@HoellerAutowired和@Autowired是等價的,能用@Autowired的地方都可以用@HoellerAutowired代替。
到此這篇關(guān)于Spring自動裝配@Autowired教程的文章就介紹到這了,更多相關(guān)Spring @Autowired內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(61)
下面小編就為大家?guī)硪黄狫ava基礎(chǔ)的幾道練習(xí)題(分享)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧,希望可以幫到你2021-08-08
Logback MDCAdapter日志跟蹤及自定義效果源碼解讀
這篇文章主要為大家介紹了Logback MDCAdapter日志跟蹤及自定義效果源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11

