Spring5.Xbean的自動裝配Autowire屬性
阿新 • • 發佈:2021-01-03
技術標籤:spring
1.屬性注⼊
前⾯學過屬性注⼊,set⽅法、建構函式等,屬於⼿⼯注⼊
有沒辦法實現⾃動裝配注⼊?
2.Spring⾃動注⼊
使⽤元素的 autowire 屬性為⼀個 bean 定義指定⾃動裝配模式
autowire設定值 :
no:沒開啟
byName: 根據bean的id名稱,注⼊到對應的屬性⾥⾯
byType:根據bean需要注⼊的型別,注⼊到對應的屬性⾥⾯ 如果按照型別注⼊,存在2個以上bean的話會拋異常 expected single matching bean but found 2
constructor: 通過建構函式注⼊,需要這個型別的建構函式
<!--autowire屬性是預設值是no,byName是根據videoOrder物件中的屬性名自動注入,byType是根據型別自動注入--> <bean id="videoOrder" class="com.xx.domain.VideoOrder" depends-on="video" autowire="byName"> <!--name是屬性名稱--> <property name="id" value="8"/> <property name="outTradeNo" value="15534e55fc"/> </bean>
測試:
public static void testInject(ApplicationContext context){ Video video1=(Video)context.getBean("video"); System.out.println(video1.getTitle()); VideoOrder videoOrder=(VideoOrder)context.getBean("videoOrder"); System.out.println(videoOrder.getVideo().getTitle()); }
測試結果:
如上圖所示:video物件被建立