天天看點

spring-注入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="listbean" class="cn.jbit.spring092901.collection.ListBean">

            <property name="list">

                <list>

                    <value>西遊記</value>

                    <value>紅樓夢</value>

                    <value>水浒傳</value>

                    <value>三國演義</value>

                </list>

            </property>

        </bean>

五.測試

    1.在項目中建立test目錄

        /test

    2.在test目錄下建立包

        cn.jbit.spring092901.collection

    3.在包下 建立測試類

        類名:ListBeanTest.java

        類内容:

        public class ListBeanTest {

            @Test

            public void testListBean(){

                ClassPathXmlApplicationContext cpac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");

                ListBean lb = (ListBean) cpac.getBean("listbean");

                List list = lb.getList();

                for (Object object : list) {

                    System.out.println(object);

                }

本文轉自  素顔豬  51CTO部落格,原文連結:http://blog.51cto.com/suyanzhu/1559508