반응형
기존 있던 Hello.java클래스에 map타입의 컬렉션 변수 하나 선언한다.
그리고 Map에 대한 getter setter만들어준다.
package myspring.di.xml;
import java.util.Map;
public class Hello {
private String name;
private Printer printer;
private Map<Integer,String> myMaps;
public Hello() {
System.out.println("Hello Default constructor called");
}
public Hello(String name, Printer printer) {
this.name = name;
this.printer = printer;
}
public void setName(String name) {
System.out.println("Hello setName() called" + name);
this.name = name;
}
public void setPrinter(Printer printer) {
System.out.println("Hello setPrinter() called" + printer.getClass().getName());
this.printer = printer;
}
public Map<Integer,String> getMyMaps() {
return myMaps;
}
public void setMyMaps(Map<Integer, String> myMaps) {
this.myMaps = myMaps;
}
public String sayHello() {
return "Hello" + this.name;
}
public void print() {
this.printer.print(sayHello());
}
}
이후 springbeans.xml 파일에 이렇게 추가해준다.
<bean id="hello" class="myspring.di.xml.Hello" scope="singleton">
<!-- Setter Injection 설정 -->
<property name="name" value="스프링이다." />
<property name="printer" ref="strPrinter" />
<property name="myMaps">
<map>
<entry key="100" value="스프링클라우드" />
<entry key="200" value="스프링배치" />
<entry key="300" value="스프링쿠버네티스" />
</map>
</property>
</bean>
테스트 소스코드
hello.getMyMap()메서드를 통해 MAP 객체를 변수에 저장한다.
그 객체의 값들은springbeans.xml파일에서 주입해준것이다.
이후 테스트 코드에서 for문돌려서 들어간 값들을 뽑아내본다.
package myspring.di.xml.test;
import java.util.Map;
import javax.annotation.Resource;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import myspring.di.xml.Hello;
import myspring.di.xml.Printer;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:config/springbeans.xml")
public class HelloBeanSpringTest {
// 이 아래걸 대체하는 어노테이션이 @ContextConfiguration
// BeanFactory factory = new GenericXmlApplicationContext("config/springbeans.xml");
@Autowired
Hello hello;
@Autowired
@Qualifier("strPrinter")
Printer printer;
@Resource(name = "helloC")
Hello hello2;
@Test@Ignore
public void constructorInjection() {
hello2.print();
}
@Test
public void setterInjection() {
Assert.assertEquals("Hello스프링이다.", hello.sayHello());
hello.print();
Assert.assertEquals("Hello스프링이다.", printer.toString());
Map<Integer, String> myMaps = hello.getMyMaps();
for (Map.Entry<Integer, String> entry : myMaps.entrySet()) {
System.out.println(entry.getKey()+ " = " + entry.getValue());
}
}
}
반응형