/java/

Dependency Injection with the Spring Framework. Xml DI. Collection.

2015-02-15 13:02:35

Yes I know, everybody love @Annotation, but it is good to know how the xml DI works.

Example

Simple example of Dependency Injection for list, map and set.

./src/main/java/pl/btbw/BeanCollectionWrapper.java

package pl.btbw;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class BeanCollectionWrapper {

    private List

<string> list;

    private Set<string> set;

    private Map<string, string=""> map;

    public List<string> getList() {
        return list;
    }

    public void setList(List<string> list) {
        this.list = list;
    }

    public Set<string> getSet() {
        return set;
    }

    public void setSet(Set<string> set) {
        this.set = set;
    }

    public Map<string, string=""> getMap() {
        return map;
    }

    public void setMap(Map<string, string=""> map) {
        this.map = map;
    }
}

./src/main/resources/application-context.xml

<?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?>
<beans beans="" http:="" schema="" spring-beans.xsd&quot;="" www.springframework.org="" xmlns='"http://www.springframework.org/schema/beans"' xmlns:xsi='"http://www.w3.org/2001/XMLSchema-instance"' xsi:schemalocation='"http://www.springframework.org/schema/beans'>
<bean class='"pl.btbw.BeanCollectionWrapper"' id='"beanCollectionWrapper"'>
<property name='"list"'>
<list>
<value>l.Value 1</value>
<value>l.Value 2</value>
<value>l.Value 3</value>
</list>
</property>
<property name='"set"'>
<set>
<value>s.Value 1</value>
<value>s.Value 2</value>
<value>s.Value 3</value>
</set>
</property>
<property name='"map"'>
<map>
<entry 1&quot;="" key='"a"' value='"m.Value'></entry>
<entry 2&quot;="" key='"b"' value='"m.Value'></entry>
<entry 3&quot;="" key='"c"' value='"m.Value'></entry>
</map>
</property>
</bean>
</beans>

How to test.

./src/main/java/pl/btbw/Application.java

package pl.btbw;

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

public class Application {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");

        BeanCollectionWrapper beanCollectionWrapper
                = context.getBean("beanCollectionWrapper", BeanCollectionWrapper.class);

        System.out.println(beanCollectionWrapper.getList());
        System.out.println(beanCollectionWrapper.getMap());
        System.out.println(beanCollectionWrapper.getSet());
    }
}

output

[l.Value 1, l.Value 2, l.Value 3]
{a=m.Value 1, b=m.Value 2, c=m.Value 3}
[s.Value 1, s.Value 2, s.Value 3]