Spring中@Autowired注解在不同方法的寫法示例
正文
今天來跟大家聊聊簡(jiǎn)單聊聊@Autowired,Autowired翻譯過來為自動(dòng)裝配,也就是自動(dòng)給Bean對(duì)象的屬性賦值。
@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)造方法上
對(duì)于@Autowired寫在構(gòu)造方法上的情況,跟Spring選擇構(gòu)造方法的邏輯有關(guān),一個(gè)類中是不是有多個(gè)構(gòu)造方法,是不是加了@Autowired注解,是不是有默認(rèn)構(gòu)造方法,跟構(gòu)造方法參數(shù)類型和個(gè)數(shù)都有關(guān)系,后面單獨(dú)來介紹。
寫在普通方法上
對(duì)于@Autowired寫在普通方法上的情況,我們通常寫的setter方法其實(shí)就是一個(gè)普通的setter方法,那非setter方法上加@Autowired會(huì)有作用嗎?
比如:
@Component
public class UserService {
@Autowired
public void test(OrderService orderService) {
System.out.println(orderService);
}
}
這個(gè)test方法會(huì)被Spring自動(dòng)調(diào)用到,并且能打印出OrderService對(duì)應(yīng)的Bean對(duì)象。
寫在方法參數(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)制依賴,如果更加某個(gè)屬性找不到所依賴的Bean是不會(huì)賦null值的,而是會(huì)報(bào)錯(cuò),如果把required屬性設(shè)置為false,則會(huì)賦null值。
寫在其他注解上
比如我們可以自定義要給注解:
@Autowired
@Retention(RetentionPolicy.RUNTIME)
public @interface HoellerAutowired {
}
@HoellerAutowired和@Autowired是等價(jià)的,能用@Autowired的地方都可以用@HoellerAutowired代替。
以上就是Spring中@Autowired注解在不同方法的寫法示例的詳細(xì)內(nèi)容,更多關(guān)于Spring @Autowired注解的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Spring boot實(shí)現(xiàn)應(yīng)用打包部署的示例
本篇文章主要介紹了Spring boot實(shí)現(xiàn)應(yīng)用打包部署的示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-11-11
Spring中BeanFactory?FactoryBean和ObjectFactory的三種的區(qū)別
關(guān)于FactoryBean?和?BeanFactory的對(duì)比文章比較多,但是對(duì)ObjectFactory的描述就比較少,今天我們對(duì)比下這三種的區(qū)別,感興趣的朋友跟隨小編一起看看吧2023-01-01
java并發(fā)編程專題(五)----詳解(JUC)ReentrantLock
這篇文章主要介紹了java(JUC)ReentrantLock的的相關(guān)資料,文中講解非常詳細(xì),實(shí)例代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-07-07
基于SpringBoot實(shí)現(xiàn)代碼在線運(yùn)行工具
這篇文章主要介紹了如何利用SpringBoot實(shí)現(xiàn)簡(jiǎn)單的代碼在線運(yùn)行工具(類似于菜鳥工具),文中的示例代碼講解詳細(xì),需要的可以參考一下2022-06-06

