亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Spring中@Autowired注解在不同方法的寫法示例

 更新時(shí)間:2023年01月10日 09:23:32   作者:Hoeller  
這篇文章主要為大家介紹了Spring中@Autowired注解在不同方法的寫法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(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可以寫在:

  • 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ú)來(lái)介紹。

寫在普通方法上

對(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

寫在屬性上

這種情況不用多說(shuō)了,值得注意的是,默認(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)文章

最新評(píng)論