您的位置:首页 > 编程语言 > Java开发

spring属性依赖注入

2015-09-02 19:57 671 查看
一、构造方法方式注入

1、项目结构如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 集合内部,普通值用value,引用值用ref -->
<bean id="collectionTestId" class="hjp.spring.attributeinject.collection.CollectionTest">
<!-- list集合 -->
<property name="listData">
<list>
<value>Jim</value>
<value>Tom</value>
<value>Jerry</value>
</list>
</property>
<!-- set集合 -->
<property name="setData">
<set>
<value>张三</value>
<value>李四</value>
<value>王五</value>
</set>
</property>
<!-- map集合 -->
<property name="mapData">
<map>
<!-- 第一种写法 -->
<entry key="A" value="a"></entry>
<entry key="B" value="b"></entry>
<entry key="C" value="c"></entry>
<!-- 第二种写法 -->
<entry>
<key>
<value>D</value>
</key>
<value>d</value>
</entry>
</map>
</property>
<!-- 数组 -->
<property name="arrayData">
<array>
<value>a</value>
<value>b</value>
<value>c</value>
</array>
</property>
<!-- Properties -->
<property name="propsData">
<props>
<prop key="X">x</prop>
<prop key="Y">y</prop>
<prop key="Z">z</prop>
</props>
</property>
</bean>
</beans>


beans
4、新建测试类

package hjp.spring.attributeinject.collection;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestApp {
@Test
public void demo1() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"hjp/spring/attributeinject/collection/beans.xml");
CollectionTest collectionTest = applicationContext.getBean("collectionTestId", CollectionTest.class);
System.out.println(collectionTest);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: