Spring Bean如何實(shí)現(xiàn)自動(dòng)配置代碼實(shí)例
自動(dòng)裝配是Spring滿足Bean依賴的一種方式;
Spring會(huì)在context中自動(dòng)尋找,并自動(dòng)給bean裝配屬性;
在Spring中有三種裝配的方式:
在xml中顯式配置 在java中顯式配置 隱式的自動(dòng)裝配bean(重要)測(cè)試
環(huán)境搭建:一個(gè)人有兩個(gè)寵物!
byName自動(dòng)裝配
<!--byName:自動(dòng)在容器上下文查找,和自己對(duì)象set方法后面的值對(duì)應(yīng)的beanid;--> <bean autowire='byName'> <property name='name' value='huba'/> </bean>
byType自動(dòng)裝配
<!--byName:自動(dòng)在容器上下文查找,和自己對(duì)象set方法后面的值對(duì)應(yīng)的beanid;byType:自動(dòng)在容器上下文查找,和自己對(duì)象屬性類型相同的bean--> <bean autowire='byName'> <property name='name' value='huba'/> </bean>
小結(jié):
byname,需要保證所有bean的id唯一,并且這個(gè)bean需要和自動(dòng)注入的屬性的set方法的值一致; byType,需要保證所有bean的class唯一,并且這個(gè)bean需要和自動(dòng)注入的屬性的類型一致;使用注解實(shí)現(xiàn)自動(dòng)裝配
jdk1.5支持的注解,spring2.5就支持注解了!
要使用注解須知:
導(dǎo)入約束:context約束
配置注解的支持:context:annotation-config/
<?xml version='1.0' encoding='UTF-8'?><beans xmlns='http://www.springframework.org/schema/beans' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:context='http://www.springframework.org/schema/context' xsi:schemaLocation='http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd'> <context:annotation-config/></beans>
@Autowired
直接在屬性上使用即可! 也可以在set方法上使用!
使用Autowired我們可以不用編寫Set方法,前提是自動(dòng)裝配的屬性在IOC容器中存在,且符合名字byname!
補(bǔ)充:
@Nullable //字段標(biāo)記了這個(gè)注解,說(shuō)明這個(gè)字段可以為nullpublic @interface Autowired {boolean required() default true;}
@Autowired(required = false)//如果顯式定義了require為false,那么這個(gè)屬性可以為null,否則不能為空
測(cè)試代碼:
public class People { @Autowired private Cat cat; @Autowired private Dog dog; private String name;}
如果@Autowired自動(dòng)裝配的環(huán)境比較復(fù)雜,自動(dòng)裝配無(wú)法通過(guò)一個(gè)注解完成時(shí),我們可以使用@Qualifier(value='xxx')去配合使用,xxx是唯一的bean對(duì)象id。
public class People { @Autowired private Cat cat; @Autowired //可以顯式的定義裝配的對(duì)象 @Qualifier(value = 'dog') private Dog dog; private String name;}
@Resource注解
public class People { @Resource(name='cat') private Cat cat; @Autowired //可以顯式的定義裝配的對(duì)象 @Qualifier(value = 'dog') private Dog dog; private String name;}
小結(jié):
@Resource和@Autowired的區(qū)別:
都是用來(lái)自動(dòng)裝配的,都可以放在屬性字段上; @Autowired先byType再byName的方式(常用) @Resource先byName再byType的方式(常用)以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. IntelliJ IDEA刪除類的方法步驟2. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法3. docker /var/lib/docker/aufs/mnt 目錄清理方法4. Intellij IDEA 關(guān)閉和開(kāi)啟自動(dòng)更新的提示?5. idea自定義快捷鍵的方法步驟6. IntelliJ IDEA導(dǎo)出項(xiàng)目的方法7. IntelliJ IDEA導(dǎo)入項(xiàng)目的方法8. 刪除docker里建立容器的操作方法9. IntelliJ IDEA配置Tomcat服務(wù)器的方法10. IntelliJ IDEA創(chuàng)建web項(xiàng)目的方法

網(wǎng)公網(wǎng)安備