Web/Spring framework
Spring) .xml을 통한 HashMap 세팅
surhommejk
2018. 4. 28. 13:11
public interface ProtocolHandler {
}
public class RestHandler implements ProtocolHandler {
}
public class RssHandler implements ProtocolHandler {
}
public class ProtocolHandlerFactory {
//Map(key , value)
private Map<String, ProtocolHandler> handlers;
public void setHandlers(Map<String, ProtocolHandler> handlers) {
this.handlers = handlers;
System.out.println("setter 주입 성공 : " + this.handlers);
}
}
public class Program {
public static void main(String[] args) {
/*
ProtocolHandlerFactory factory = new ProtocolHandlerFactory();
Map<String, ProtocolHandler> map = new HashMap<>();
map.put("rss", new RssHandler());
map.put("rest", new RestHandler());
factory.setHandlers(map);
*/
ApplicationContext context =
new GenericXmlApplicationContext("classpath:DI_09_Spring/DI_09.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
IOC 컨테이너 (Spring 전용 메모리 공간) 안에
생성될 객체를 만들고 조립(의존)관계 설정 하는 파일
ProtocolHandlerFactory factory = new ProtocolHandlerFactory();
Map<String, ProtocolHandler> map = new HashMap<>();
map.put("rss", new RssHandler());
map.put("rest", new RestHandler());
factory.setHandlers(map);
-->
<bean id="factory" class="DI_09_Spring.ProtocolHandlerFactory">
<property name="handlers">
<map>
<entry>
<key><value>rss</value></key>
<ref bean="rsshandler" />
</entry>
<entry>
<key><value>rest</value></key>
<!-- 이렇게 bean을 만들면서 여기서 넣어도 된다 -->
<bean class="DI_09_Spring.RestHandler"></bean>
</entry>
</map>
</property>
</bean>
<!-- 이렇게 bean을 만들어서 위에서 bean id로 넣어도 된다 -->
<bean id="rsshandler" class="DI_09_Spring.RssHandler" ></bean>
</beans>