Spring简单类型依赖注入有4种方式:
1.1 构造器注入
<bean name="car" class="com.roxy.spring.pojo.Car">
<property name="name" value="小黄车"></property>
<property name="color" value="yellow"></property>
</bean>
<bean name="personByConstructor" class="com.roxy.spring.pojo.Person">
<constructor-arg name="name" value="draco"></constructor-arg>
<constructor-arg name="age" value="17"></constructor-arg>
<constructor-arg name="car" ref="car"></constructor-arg>
</bean>
6.1.1 如果构造器方法相同,但是传递参数的顺序不同,可以通过index确定参数的位置:
public Person(String name, Integer age, Car car){}
public Person(Integer age, String name, Car car){}
<bean name="personByConstructor1" class="com.roxy.spring.pojo.Person">
<constructor-arg name="name" value="harry" index="1"></constructor-arg>
<constructor-arg name="age" value="17" index="0"></constructor-arg>
<constructor-arg name="car" ref="car" index="2"></constructor-arg>
</bean>
6.1.2 如果构造器方法相同,但是传递参数的类型不同,可以用type确定参数的位置:
public Person(Integer age, Car car, String name)
public Person(Integer age, Car car, Integer name)
<bean name="personByConstructor2" class="com.roxy.spring.pojo.Person">
<constructor-arg name="name" value="000" type="java.lang.Integer"></constructor-arg>
<constructor-arg name="age" value="17"></constructor-arg>
<constructor-arg name="car" ref="car"></constructor-arg>
</bean>
1.2 setter方法注入
<bean name="personBySet" class="com.roxy.spring.pojo.Person">
<property name="name" value="draco"></property>
<property name="age" value="17"></property>
<property name="car" ref="car"></property>
</bean>
1.3 p命名空间注入
xmlns:p="http://www.springframework.org/schema/p"
<bean name="personByP" class="com.roxy.spring.pojo.Person" p:name="homine" p:age="17" p:car-ref="car"></bean>
典型案例:
配置数据源
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/mydb"
p:username="root"
p:password="masterkaoli"/>
1.4 spEL表达式注入
<bean name="personBySPEL" class="com.roxy.spring.pojo.Person">
<property name="name" value="#{personBySet.name}"></property>
<property name="age" value="#{personBySet.age}"></property>
<property name="car" ref="car"></property>
</bean>
Spring复杂对象类型的依赖注入:
<bean name="myCollection" class="com.roxy.spring.pojo.MyCollection"> <property name="arr"> <array> <value>ios1</value> <value>ios1</value> </array> </property> <property name="stringSet"> <set> <value>linux2</value> <value>linux2</value> </set> </property> <property name="stringList"> <list> <value>java3</value> <value>java3</value> </list> </property> <property name="stringMap"> <map> <entry> <key> <value>1</value> </key> <value>html5</value> </entry> <entry> <key> <value>2</value> </key> <value>javascript</value> </entry> </map> </property> <property name="stringProperties"> <props> <prop key="001">001</prop> <prop key="010">010</prop> </props> </property> </bean>