'뉴렉처' 님의 채널(www.youtube.com/user/newlec1)을 바탕으로 제작한 블로그 글입니다:)
이번 시간에는 collection 타입의 bean을 생성해보고, 콜렉션 형식은 어떻게 DI 지시서로 작성하는지 알아보도록 하겠습니다.
이전 시간에는, setter을 이용해서 부품끼리 결합시키는 방법을 배웠었는데요,
이번에는 setter가 아닌 다른 방식으로 setting하는 경우에는 어떻게 DI 지시서를 작성하는지 알아보려고 합니다!
우선 setter가 아닌 다른 방식은 어떤 것들이 있는지 아래의 예시를 들어보도록 하겠습니다.
List<Animal> mylist = new ArrayList<>();
mylist.add(new Animal("MINA", 10));
위의 코드를 보면, mylist를 생성한 다음에, add로 list에 객체를 넣어주는 모습을 볼 수 있습니다.
즉, setter가 아닌 add를 사용하기 때문에 아래와 같은 property는 사용할 수 없는 것이죠.
// console.setAnimal(animal);
<bean id = "console" class = "spring.console.AnimalPrintName">
<property name = "animal" ref = "animal"/>
</bean>
그렇다면 위와 같은 경우는 어떻게 해결해야 하는지 알아봅시다.
우선, List<Animal> mylist = new ArrayList<>() 와 같은 경우에는, 객체를 새로 생성하는 부분이기 때문에 이미 배운 적이 있습니다.
아래와 같이 적어주어야겠죠.
- Program.java
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("spring/di/setting.xml");
AnimalPrint console = (AnimalPrint) context.getBean("console");
// List<Animal> mylist = new ArrayList<>();
List<Animal> mylist = (List<Animal>) context.getBean("mylist");
mylist.add(new Animal("MINA", 10));
for (Animal item : mylist){
System.out.println("Name : " + item.getName() + "\nAge : " + item.getAge());
}
}
- setting.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id = "animal" class = "spring.entity.Animal" p:name="BINGO" p:age="10"/>
<bean id = "console" class = "spring.console.AnimalPrintName">
<property name = "animal" ref = "animal"/>
</bean>
<bean id = "mylist" class = "java.util.ArrayList"></bean>
</beans>
위의 코드를 입력하고, 실행시켜보면 객체 생성 부분 DI가 잘 이루어져서 제대로 정보가 출력되는 걸 볼 수 있습니다.
그러면 이제 list에 우리가 원하는 값들을 넣어주려면 어떻게 해야할까요?
ArrayList 생성자의 인자 중에서, ArrayList(Collection c) 라는 것이 있습니다.
지금부터 이 Collection 이라는 것을 이용해서 외부 설정으로 객체를 넣어주는 작업을 해보겠습니다!
우선 생성자에 인자를 넣어주는 방식이니, constructor-arg 태그가 필요합니다.
그 다음, 현재 collection을 사용해야 하므로, list라는 태그를 이용해줍니다.
마지막으로 list 태그 안에 추가하고 싶은 내용들을 넣어줍니다.
이 때 안에 들어갈 수 있는 형식은 다양한데, 먼저 아래의 방식을 이용하여 collection을 생성하도록 하겠습니다.
<bean id = "mylist" class = "java.util.ArrayList">
<constructor-arg>
<list>
<bean class = "spring.entity.Animal" p:name="ALEX" p:age="5"/>
<ref bean="animal"/>
</list>
</constructor-arg>
</bean>
위의 코드를 하나씩 살펴봅시다.
list 내에 bean 객체로 Animal class의 객체를 넣어주는 방법과,
ref 태그를 이용하여 이미 만들어진 bean 객체를 가져와 넣어주는 방법을 갖고 있습니다.
실행해주면 list에 객체를 넣어준 순서대로 결과가 잘 나오는 것을 볼 수 있습니다.
위처럼 생성자에 list를 넣지 않고, collection을 따로 만들어주는 방법도 사용할 수 있습니다.
그러기 위해서는 util이라는 namespace가 필요한데요, setting.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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
...
이전에는 생성자 내에서 자체적으로 객체를 만들 수 없었지만,
이제는 util이라는 처리기의 도움으로 자체적으로 객체를 만들수 있게 됩니다.
그 후, list를 사용할 수 있는 class가 무엇인지 알려주기 위해서, class="java.util.ArrayList" 를 적어줍니다.
마지막으로, util:.list에 대한 이름을 id로 정의해줍니다.
이를 통해서 값이나 참조 대상이 java.util.List인 빈을 만들 수 있습니다.
그러면 아래와 같은 코드가 완성됩니다.
<?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"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<bean id = "animal" class = "spring.entity.Animal" p:name="BINGO" p:age="10"/>
<bean id = "console" class = "spring.console.AnimalPrintName">
<property name = "animal" ref = "animal"/>
</bean>
<util:list id = "mylist" list-class = "java.util.ArrayList">
<bean class = "spring.entity.Animal" p:name="ALEX" p:age="5"/>
<ref bean="animal"/>
</util:list>
</beans>
실행시켜보면 이전과 동일하게 잘 나오는 것을 볼 수 있습니다.
'Spring > Dependency Injection' 카테고리의 다른 글
[Spring Framework] @Qualifier 를 사용하는 이유 (0) | 2021.01.17 |
---|---|
[Spring Framework] 어노테이션과 @Autowired 사용하기 (0) | 2021.01.15 |
[Spring Framework] Spring Bean Configuration (DI 지시서) 작성법 (2) (0) | 2021.01.06 |
[Spring Framework] 이클립스에서 Spring Library 가져오기 (0) | 2021.01.06 |
[Spring Framework] Application Context 사용하기 (0) | 2021.01.05 |