基于配置文件的Spring注入

基于配置文件的Spring注入

 

一、依赖注入的概述

依赖注入指的是经过Spring配置文件的方式建立对象时,直接经过配置的方式将数据注入到该对象的标量类型属性,并从Spring容器中获取指定对象注入到该对象的引用属性中。依赖注入的方式有:java

①set方法注入;               ②构造方法注入 ;               ③p标签注入。

 

 

二、<property>标签——set方法注入

①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方法实际名与其对应属性名相同)数组

 

 

三、<constructor-arg>标签——构造方法注入

①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:[属性名]”和“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>
 

六、注入Properties文件的数据

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   万有引力+

 

-

 

-

 

-

 

-

 

-

相关文章
相关标签/搜索