依賴注入指的是經過Spring配置文件的方式建立對象時,直接經過配置的方式將數據注入到該對象的標量類型屬性,並從Spring容器中獲取指定對象注入到該對象的引用屬性中。依賴注入的方式有:java
①name屬性:指定set方法實際名; ② value屬性:設置標量型數值; ③ref屬性:指定注入對象。spring
<bean name="now" class="java.util.Date"></bean> <bean name="customerService" class="cn.gzsxt.service.CustomerService"> <property name="name" value="zhangsan"></property> <property name="birthday" ref="now"></property> </bean>
(注:使用系統生成的set方法,set方法實際名與其對應屬性名相同)數組
①name屬性:指定構造方法參數名; ②index屬性:指定對應參數的位置;post
③value屬性:設置標量型數值; ④ref屬性:指定注入對象。 編碼
<bean name="now" class="java.util.Date"></bean> <bean name="customerService" class="cn.gzsxt.service.CustomerService"> <constructor-arg name="name" value="zhangsan"></constructor-arg> <constructor-arg name="age" value="15"></constructor-arg> <constructor-arg index="2" ref="now"></constructor-arg> </bean>
(注:使用<constructor-arg>標籤注入,必須存在與注入參數徹底匹配的構造方法)spa
引入p標籤,以「p:[屬性名]」和「p:[屬性名]-ref 」做爲<bean>標籤的屬性來注入數據。code
<bean name="now" class="java.util.Date"></bean> <bean name="customerService" class="cn.gzsxt.service.CustomerService" p:name="zhangsan" p:age="15" p:birthday-ref="now"> </bean>
Spring對於注入數組、List、Set、Map、和Properties等結構的數據,分別提供了特定的標籤來注入。對象
<!-- 數組類型 --> <property name="arr01"> <array> <value>A</value> <value>B</value> <value>C</value> </array> </property>
<!-- Set類型 --> <property name="set02"> <set> <value>D</value> <value>E</value> <value>F</value> </set> </property>
<!-- List類型 --> <property name="list03"> <list> <value>G</value> <value>H</value> <value>I</value> </list> </property> <!-- Map類型 --> <property name="map04"> <map> <entry key="name" value="zhangsan"/> <entry key="birthday" value-ref="now"></entry> </map> </property> <!-- Properties類型 --> <property name="props05"> <props> <prop key="id">1</prop> <prop key="name">zhangsan</prop> </props> </property>
Spring對Properties文件的支持,是基於opertySourcesPlaceholderConfigurer類實現的;經過Properties文件注入,必須指定其文件的路徑。blog
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"> <property name="locations" value="classpath:sys.properties"></property> <property name="fileEncoding" value="UTF-8"></property> </bean> <bean name="customerService" class="cn.gzsxt.service.CustomerService"> <property name="name" value="${customer.name}"></property> <property name="age" value="${customer.age}"></property> </bean>
(注:①加載Properties文件能夠使用<context:property-placeholder file-encoding = "UTF-8" location = "classpath:sys.properties" />標籤代替;②Properties文件默認編碼格式爲ISO-8859-1,須要設置爲其餘編碼才支持中文)io
———————————————————————————————————————————————————————————————————
The end @ 萬有引力+
-
-
-
-
-