Spring - 콜렉션 생성과 DI

jodbsgh·2022년 3월 30일
0

🍕"Spring"

목록 보기
11/19

xml파일을 통해서 주입 없이, JAVA문으로 컬렉션객체를 생성했을 때

List <Exam> exams = new ArrayList<>();

exams.add(new NewlecExam(1,1,1,1));

for(Exam e : exams)		//exams 배열에서 값을 하나씩 출력해라 forEach문
	System.out.println(e);

xml을 통해서 컬렉션 주입하기

List<Exam> exams = context.getBean("exams");	//new ArrayList
exams.add(new NewlectExam(1,1,1,1));

for(Exam e : exams)
	System.out.println(e);
xml파일)

<beans>
	<!--id = 주입할 객체명 , class=경로 -->
	<bean id="exams" class="java.util.ArrayList">
    	<constructor-arg>
        	<list>
            	<!-- 직접 생성
                Spring.di.entity.NewlecExam 경로에서 추가
                -->
            	<bean id="" class="Spring.di.entity.NewlecExam" 
                p:kor="10" p:eng="20" p:math="30" p:com="40"/>
                <!--참조해서 추가 -->
                <ref bean="exam"/>
            </list>
        </constructor-arg>
    </bean>
</beans>
<util:list>  <!-- 객체를 만드는 역할을 할 수 있음 -->
	<bean/>
    <ref/>
</util:list> 

<constructor-arg> <!-- 이 자체가 객체를 만드는 역할을 하진 못함-->
	<list>
		<bean/>
  	    <ref/>
    </list>
</constructor-arg>


<!-- 따라서 위의 코드를 이런식으로 변경이 가능하다.	-->
<beans>
	<!--id = 주입할 객체명 , class=경로 -->
	<bean id="exams" class="java.util.ArrayList">
       	<util:list>	<!--이전보다 코드의 길이를 줄일 수 있음-->
            <bean id="" class="Spring.di.entity.NewlecExam" 
            p:kor="10" p:eng="20" p:math="30" p:com="40"/>
            <ref bean="exam"/>
        </util:list>
    </bean>
</beans>

이처럼 xml을 통해서 컬렉션 객체 생성을 요청할 수 있다.

profile
어제 보다는 내일을, 내일 보다는 오늘을 🚀

0개의 댓글