Thursday, 5 April 2018

Spring CI with collections

We can inject the collection values by constructor in spring frame work. We can inject the list as follows.

package com.bk.spring.test;

import java.util.List;

public class EmployeeBean {

    private String id;
    private String name;
    private List<String> projects;
   
    public EmployeeBean(String id, String name, List<String> projects){
        this.id = id;
        this.name = name;
        this.projects = projects;
    }
   
    public void displayEmplyeeDetails(){
        System.out.println("employee details are " + id + " ");
        System.out.println("id is " + id);
        System.out.println("name is " + name);
        System.out.println("projects are " );
        for (String string : projects) {
            System.out.println(string);
        }
    }
}

<?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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
       <bean name="employeeBean" class="com.bk.spring.test.EmployeeBean">
        <constructor-arg value="0000001" />
        <constructor-arg value="Krishna" />
        <constructor-arg>
            <list>
                <value>Java Project</value>
                <value>J2EE Project</value>
                <value>Spring Project</value>
            </list>
        </constructor-arg>
    </bean>
</beans>


package com.bk.spring.test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class SpringConDITest {

    public static void main(String a[]) {

        Resource res = new ClassPathResource("applicationContext.xml");
        BeanFactory factory = new XmlBeanFactory(res);
    
        EmployeeBean employeeBean = (EmployeeBean) factory.getBean("employeeBean");
        employeeBean.displayEmplyeeDetails();

    }

}

No comments:

Post a Comment