8. 컬렉션 생성

Seungjae·2021년 1월 24일
0

Spring 다지기

목록 보기
8/14

컬렉션 생성


DI명세서를 이용해서 컬렉션 또한 생성할 수 있습니다.

List<Exam> examList = new ArrayList<>();
examList.add(new OhExam(1,1,1,1));
		
for(Exam e : examList) {
	System.out.println(e);
}

기본 예제 코드입니다. 위에 ArrayList객체를 생성하는 부분을 아래처럼 바꿔줄 수 있습니다.

List examList = (List) context.getBean("examList"); // new ArrayList<>();

이때 DI명세서에는 list태그를 이용해서 컬렉션을 생성해줍니다.

<bean id="examList" class="java.util.ArrayList"> 컬렉션 추가
	<constructor-arg>
		<list>
			<bean class="spring.di.entity.OhExam" p:korean="1" p:english="1" />
			<ref bean="exam" /> 위에 id가 exam인 것을 참조!
		</list>
	</constructor-arg>
</bean>

위 방식도 가능하지만 네임스페이스를 이용하면 더욱 간단하게 컬렉션을 만들 수 있습니다.

xmlns:util="http://www.springframework.org/schema/util"

<util:list id="examList" list-class="java.util.ArrayList">
	<bean class="spring.di.entity.OhExam" p:korean="1" p:english="1" />
	<ref bean="exam" /> <!-- 위에 id가 exam인 것을 참조! -->
</util:list>
profile
코드 품질의 중요성을 아는 개발자 👋🏻

0개의 댓글

관련 채용 정보