欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring中@Autowired注解在不同方法的寫(xiě)法示例

 更新時(shí)間:2023年01月10日 09:23:32   作者:Hoeller  
這篇文章主要為大家介紹了Spring中@Autowired注解在不同方法的寫(xiě)法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

正文

今天來(lái)跟大家聊聊簡(jiǎn)單聊聊@Autowired,Autowired翻譯過(guò)來(lái)為自動(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可以寫(xiě)在:

  • ElementType.CONSTRUCTOR:表示可以寫(xiě)在構(gòu)造方法上
  • ElementType.METHOD:表示可以寫(xiě)在普通方法上
  • ElementType.PARAMETER:表示可以寫(xiě)在方法參數(shù)前
  • ElementType.FIELD:表示可以寫(xiě)在屬性上
  • ElementType.ANNOTATION_TYPE:表示可以寫(xiě)在其他注解上

寫(xiě)在構(gòu)造方法上

對(duì)于@Autowired寫(xiě)在構(gòu)造方法上的情況,跟Spring選擇構(gòu)造方法的邏輯有關(guān),一個(gè)類(lèi)中是不是有多個(gè)構(gòu)造方法,是不是加了@Autowired注解,是不是有默認(rèn)構(gòu)造方法,跟構(gòu)造方法參數(shù)類(lèi)型和個(gè)數(shù)都有關(guān)系,后面單獨(dú)來(lái)介紹。

寫(xiě)在普通方法上

對(duì)于@Autowired寫(xiě)在普通方法上的情況,我們通常寫(xiě)的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ì)象。

寫(xiě)在方法參數(shù)前

把@Autowired寫(xiě)在參數(shù)前沒(méi)有多大意義,只在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

寫(xiě)在屬性上

這種情況不用多說(shuō)了,值得注意的是,默認(rèn)情況下,因?yàn)锧Autowired中的required屬性為true,表示強(qiáng)制依賴(lài),如果更加某個(gè)屬性找不到所依賴(lài)的Bean是不會(huì)賦null值的,而是會(huì)報(bào)錯(cuò),如果把required屬性設(shè)置為false,則會(huì)賦null值。

寫(xiě)在其他注解上

比如我們可以自定義要給注解:

@Autowired
@Retention(RetentionPolicy.RUNTIME)
public @interface HoellerAutowired {
}

@HoellerAutowired和@Autowired是等價(jià)的,能用@Autowired的地方都可以用@HoellerAutowired代替。

以上就是Spring中@Autowired注解在不同方法的寫(xiě)法示例的詳細(xì)內(nèi)容,更多關(guān)于Spring @Autowired注解的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論