首页 > 代码库 > spring-通过ListFactory注入List
spring-通过ListFactory注入List
一.创建项目
项目名称:spring092901
二.添加jar包
commons-logging.jar
junit-4.4.jar
log4j.jar
spring-beans-3.2.0.RELEASE.jar
spring-context-3.2.0.RELEASE.jar
spring-core-3.2.0.RELEASE.jar
spring-expression-3.2.0.RELEASE.jar
三.添加配置文件
1.在项目中创建conf目录
/conf
2.在conf目录下添加配置文件
配置文件名称:applicationContext.xml
配置文件内容:
<?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:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
</beans>
四.创建业务bean
1.在src下创建包
包名:cn.jbit.spring092901.collection
2.在包下创建bean
bean名称:ListBean.java
bean内容:
public class ListBean {
private List list;
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
}
3.在核心配置文件中配置bean
<bean id="listbyFactoryBean" class="cn.jbit.spring092901.collection.ListBean">
<property name="list">
<bean class="org.springframework.beans.factory.config.ListFactoryBean">
<property name="targetListClass">
<value>java.util.ArrayList</value><!-- 不能写List -->
</property>
<property name="sourceList">
<list>
<value>老子</value>
<value>庄子</value>
<value>孔子</value>
<value>孙子</value>
</list>
</property>
</bean>
</property>
</bean>
五.测试
1.在项目中创建test目录
/test
2.在test目录下创建包
cn.jbit.spring092901.collection
3.在包下 创建测试类
类名:ListbyFactoryBeanTest.java
类内容:
public class ListbyFactoryBeanTest {
/*
* 通过ListFactoryBean方式
*/
@Test
public void testListFactoryBean(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
ListBean lb = (ListBean) context.getBean("listbyFactoryBean");
for (Object object: lb.getList()) {
System.out.println(object);
}
}
}
本文出自 “素颜” 博客,请务必保留此出处http://suyanzhu.blog.51cto.com/8050189/1559501
spring-通过ListFactory注入List