属性的依赖注入:
1.构造注入:
<bean id="" class="">
<constructor-arg name="username" value/ref=""></constructor-arg>
</bean>
name为需要注入的对象实例的名称,如username,age,但是一般开发中可能不知道源码中的值
可以用index=“0”/“1"参数索引号进行设置,还可同时加上type=”"更精确匹配
<bean id="userDao" class="edu.cn.dao.Impl.UserDaoImpl"/>
<bean id="userService" class="edu.cn.service.Impl.UserServiceImpl">
<constructor-arg>
<ref bean="userDao"/>
</constructor-arg>
</bean>
2.p命名空间注入:略
(对set方法进行了简化,替换了原有的 property 标签)
3.集合注入:
collData类(collection集合)
public class collData{
私有属性
private String[] arrayData;
private List listData;
private set setData;
private Map<String,String> mapData;
private properties propsData;
并加上对应的get/set/toString方法
}
TestColl类
public void demo throws Exception{
String xmlpath =“com.···.beans.xml”
ApplicationContext applicationContext= new ClassPathXmlApplicationContext(xmlpath);
CollData customer=(CollData)applicationContext.getBean(“collDataId”);
suystem.out.println(customer);
}
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="collDataId" class="com.~.CollData">
<!-- 给数组注入值 -->
<property name="arrayData">
<array>
<value>A</value>
<value>B</value>
<value>C</value>
</array>
</property>
<!-- 给list注入值 可以有相同的多个对象 -->
<property name="empList">
<list>
<ref bean="参考1的ID" />
<ref bean="参考2的ID"/>
</list>
</property>
<!-- 给set注入值 不能有相同的对象 -->
<property name="empSets">
<set>
<ref bean="参考1的ID" />
<ref bean="参考2的ID"/>
</set>
</property>
<!-- 给map注入值 只要map中的key值不一样就可以装配value -->
<property name="empMap">
<map>
<entry key="1" value-ref="参考1的ID" />
<entry key="2" value-ref="参考2的ID" />
</map>
</property>
<!-- 给属性集合配置 -->
<property name="propsData">
<props>
<prop key="p1">aaa</prop>
<prop key="p2">bbb</prop><!--字符串值不用加引号-->
</props>
</property>
</bean>
</beans>