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

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

 更新時間:2023年01月10日 09:23:32   作者:Hoeller  
這篇文章主要為大家介紹了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的定義,重點看 @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注解,是不是有默認構(gòu)造方法,跟構(gòu)造方法參數(shù)類型和個數(shù)都有關(guān)系,后面單獨來介紹。

寫在普通方法上

對于@Autowired寫在普通方法上的情況,我們通常寫的setter方法其實就是一個普通的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

寫在屬性上

這種情況不用多說了,值得注意的是,默認情況下,因為@Autowired中的required屬性為true,表示強制依賴,如果更加某個屬性找不到所依賴的Bean是不會賦null值的,而是會報錯,如果把required屬性設(shè)置為false,則會賦null值。

寫在其他注解上

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

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

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

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

相關(guān)文章

最新評論