久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

Spring注解實現(xiàn)自動裝配過程解析

瀏覽:7日期:2023-09-14 15:46:54

在IOC容器中學(xué)習(xí)相關(guān)注解(常用)

1. @Autowireda.作用對象:(官網(wǎng)解釋)

1. You can apply the @Autowired annotation to constructors:

2.you can also apply the @Autowired annotation to 'traditional' setter methods:

3.You can also apply the annotation to methods with arbitrary names and/or multiple arguments:

4.You can apply @Autowired to fields as well and even mix it with constructors:

5.It is also possible to provide all beans of a particular type from the ApplicationContext by adding the annotation to a field or method that expects an array of that type:

6.Even typed Maps can be autowired as long as the expected key type is String. The Map values will contain all beans of the expected type, and the keys will contain the corresponding bean names:等

總結(jié)一下就是: 可以在構(gòu)造器,set方法,任意方法和屬性上,數(shù)組上,String類型的Map上等。

Notes:1.@Autowired默認按類型裝配(這個注解是屬業(yè)spring的),默認情況下必須要求依賴對象必須存在,如果要允許null值,可以設(shè)置它的required屬性為false。

2.可以與@qualifier 共同使用, 當(dāng)對象類型和名字發(fā)生沖突時,該注解可用于指定特定的對象。

@Autowired() @Qualifier('cat')

可以找到id='cat'的beanb.功能:它可以對類成員變量、方法及構(gòu)造函數(shù)進行標注,完成自動裝配的工作。通過 @Autowired的使用來消除 set ,get方法。2.@Resourcea.功能: @Resource的作用相當(dāng)于@Autowired,只不過@Autowired按byType自動注入,而@Resource默認按 byName自動注入

@Resource有兩個屬性是比較重要的,分是name和type,Spring將@Resource注解的name屬性解析為bean的名字,而type屬性則解析為bean的類型。所以如果使用name屬性,則使用byName的自動注入策略,而使用type屬性時則使用byType自動注入策略。如果既不指定name也不指定type屬性,這時將通過反射機制使用byName自動注入策略。

3.@Requireda.功能:@Required 注釋應(yīng)用于 bean 屬性的 setter 方法,它表明受影響的 bean 屬性在配置時必須放在 XML 配置文件中,否則容器就會拋出一個 BeanInitializationException 異常。下面顯示的是一個使用 @Required 注釋的示例。

這有一個很好的解釋和例子關(guān)于@Required注解

使用@Autowired后的優(yōu)點

原來我們需要手動注入之后才可以使用employee對象:

<bean> <property name='employee' ref='employee'/>

若沒有進行手動注入,不會從測試代碼中 獲取到employee對象。

使用@Autowired之后

不需要手動注入。

<bean />

只用在屬性上進行@Autowired注釋標注

Spring注解實現(xiàn)自動裝配過程解析

在測試類中即可直接調(diào)用:

public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext('applicationContext.xml'); Car car = (Car) context.getBean('car'); car.getOwner().MyEmployment(); }}

系統(tǒng)首先根據(jù) bean中class類型進行確認,再和bean中id名進行確認,最后確定所定的注入對象。 若多個bean 名字不同,且類型相同則該注釋失效。(可使用@Qualifier 進行唯一指定)

例如:

<bean /> <bean />

運行相同代碼會報如下錯誤:

Spring注解實現(xiàn)自動裝配過程解析

此時加上@Qualifier注釋如下,代碼可正常編譯:

Spring注解實現(xiàn)自動裝配過程解析

運行結(jié)果:

Spring注解實現(xiàn)自動裝配過程解析

如分享內(nèi)容中有問題的地方,還望您多加指出,感謝您的瀏覽。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標簽: Spring
相關(guān)文章:
主站蜘蛛池模板: 英德市| 仲巴县| 桐梓县| 安塞县| 长治市| 且末县| 丹江口市| 葫芦岛市| 东莞市| 涟源市| 张家川| 滨州市| 高邮市| 桦南县| 肇州县| 宣化县| 外汇| 通辽市| 陕西省| 桂东县| 保康县| 杂多县| 汉中市| 凯里市| 长丰县| 枣阳市| 大新县| 拉萨市| 莱阳市| 加查县| 布尔津县| 珲春市| 淄博市| 锡林郭勒盟| 桐庐县| 新野县| 交城县| 大关县| 乃东县| 平阴县| 株洲县|