반응형

[Spring] Spring에서 새터(Setter)로 리스트(List), 맵(Map) 자료구조 주입

반응형


| 리스트(List) 및 맵(Map) 자료구조 주입


xml 설정 파일 상에서 새터(Setter) 방식을 이용하여 자바의 리스트(List) 혹은 맵(Map)에 의존성을 주입할 수 있다.


<?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">

<bean id="resturant1" class="com.tutorial.spring.Resturant">
<property name="names">
<list>
<value>Duke</value>
<value>Mario</value>
<value>Suzy</value>
<value>Kate</value>
</list>
</property>

<property name="menus">
<map>
<entry>
<key>
<value>1</value>
</key>
<value>KingCrap</value>
</entry>
<entry>
<key>
<value>2</value>
</key>
<value>IceCream</value>
</entry>
<entry>
<key>
<value>3</value>
</key>
<value>Pork</value>
</entry>
</map>
</property>
</bean>
</beans>

<appContext2.xml 설정파일>

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.support.GenericXmlApplicationContext;

class Resturant {

private List<String> names;
private Map<Integer, String> menus;

Resturant(){
names = new ArrayList<>();
menus = new HashMap<>();
}

public List<String> getNames() {
return names;
}

public void setNames(List<String> names) {
this.names = names;
}

public Map<Integer, String> getMenus() {
return menus;
}

public void setMenus(Map<Integer, String> menus) {
this.menus = menus;
}
}

public class App {

public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:appContext2.xml");
Resturant resturant = ctx.getBean("resturant1", Resturant.class);

System.out.println("--- names property ---");
resturant.getNames().stream().forEach(System.out::println);
System.out.println("--- menus property ---");
resturant.getMenus().forEach((k, v) -> {
System.out.println("key : " + k + " " + "value : " + v);
});
}
}

1128, 2018 11:15:32 오후 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
정보: Loading XML bean definitions from class path resource [appContext2.xml]
1128, 2018 11:15:32 오후 org.springframework.context.support.AbstractApplicationContext prepareRefresh
정보: Refreshing org.springframework.context.support.GenericXmlApplicationContext@439f5b3d: startup date [Wed Nov 28 23:15:32 KST 2018]; root of context hierarchy
1128, 2018 11:15:32 오후 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
정보: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@59a6e353: defining beans [resturant1]; root of factory hierarchy
--- names property ---
Duke
Mario
Suzy
Kate
--- menus property ---
key : 1 value : KingCrap
key : 2 value : IceCream
key : 3 value : Pork


<실행 자바 코드>

반응형

이 글을 공유하기

댓글

Designed by JB FACTORY