본문 바로가기

JAVA/Spring

[Spring] 기존 MVC방식부터 스프링까지 간단한 프로젝트 생성 (3)

<다양한 생성자 DI>

(DI : Dependancy Injection)

ExamImpl 클래스에 롬복등으로 생성자를 생성한 상태여야함.

	<bean id="exam" class="spring.di.entity.ExamImpl">
		<constructor-arg index="0" value="10" />
		<constructor-arg index="1" value="20" />
		<constructor-arg index="2" value="30" />
		<constructor-arg index="3" value="40" />
	</bean>
	<bean id="exam" class="spring.di.entity.ExamImpl">
		<constructor-arg name="kor" value="10" />
		<constructor-arg name="eng" value="20" />
		<constructor-arg name="math" value="30" />
		<constructor-arg name="com" value="40" />
	</bean>
<bean id="exam" class="spring.di.entity.ExamImpl" p:kor="10" p:eng="20" p:math="30" p:com="40" />

이 때 p에 빨간줄이 가면 이클립스 편집창 하단 source 옆에 namespace탭 클릭 후 p에 체크

 

 

<리스트 생성해보기>

기존의 리스트 생성은 아래와 같이 할 수 있을것이다.

public class Program {
	public static void main(String[] args) {
		List<Exam> examlist = new ArrayList<>();
		examlist.add(new ExamImpl(20,30,40,50));
		for(Exam e : examlist) {
			System.out.println(e);
		}
	}
}

이를 스프링을 이용하여 처리하면 다음과 같다. 자바에선 지시만 하고 ArrayList<Exam>()은 지시서에서 가져와야한다. 

public class Program {
	public static void main(String[] args) {
		List<Exam> examlist = (List<Exam>) context.getBean("examlist"); 
		for(Exam e : examlist) {
			System.out.println(e);
		}
	}
}

 

방법 1

<bean id="examlist" class="java.util.ArrayList">
    <constructor-arg>
        <list>
            <bean id="exam" class="spring.di.entity.ExamImpl" p:kor="10" p:eng="20" p:math="30" p:com="40" />
            <ref bean="exam" />
        </list>
    </constructor-arg>
</bean>

 

방법 2

위의 방법이 너무 길다면 namespace에서 유틸에 체크한 뒤 아래와 같이 표기할 수 있다. 허나 위의 코드와 아래 코드는 하는 역할은 같으나 다른 형식이다. (나도 정확히 어떻게 다른지는 모르겠다ㅡㅡ;)

	<util:list id="examlist" list-class="java.util.ArrayList">
		<bean id="exam" class="spring.di.entity.ExamImpl" p:kor="10" p:eng="20" p:math="30" p:com="40" />
		<ref bean="exam" />
	</util:list>
728x90