백엔드/Spring

Spring - 생성자 DI | TIL_152

ran4 2022. 10. 12. 23:33

https://www.youtube.com/playlist?list=PLq8wAnVUcTFUHYMzoV2RoFoY2HDTKru3T

스프링 강의를 듣고 정리한 내용입니다

 


 

Constructor를 이용한 속성 값 설정

NewlecExam 생성자 추가

public NewlecExam() {
}

public NewlecExam(int kor, int eng, int math, int com) {
this.kor = kor;
this.eng = eng;
this.math = math;
this.com = com;
}

 

태그 추가 

<bean id="exam" class="spring.di.entity.NewlecExam">
<constructor-arg value="30"/> <!-- constructor argument -->
<constructor-arg value="50"/>
<constructor-arg value="70"/>
<constructor-arg value="70"/>
</bean>

 

▷ 문제점 : 각 객체에 해당하는 순서를 알 수 없다

 

 

해결법

 

1. index를 추가한다

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

 

 

 

2. index 대신 name을 사용한다

<bean id="exam" class="spring.di.entity.NewlecExam">
<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>

 

 

위의 태그를 사용하기 위하여 NewlecExam 클래스에 toString() 메서드를 추가한다 

-> 값을 출력하는 문자열을 포함할 수 있다

 

※ 커맨드로 간편하게 추가가 가능하다

이클립스

alt + shift + s를 누르고 generate toString을 클릭한다

 

인텔리제이

alt + insert를 눌러 추가해준다

 

 

 

Program에 toString()을 출력하는 코드 추가 

Exam exam = context.getBean(Exam.class);
System.out.println(exam.toString());

 

 

 

생성자 호출시 자료형이 다른 경우

▶ type을 이용한다

<constructor-arg type="float" value="10"/>

<constructor-arg type="float" value="20"/>

<constructor-arg type="float" value="30"/>

 

 

 

단일 태그를 이용하여 속성 설정

<bean id="exam" class="spring.di.entity.NewlecExam"
p:kor="10" p:eng="10" p:com="10" p:math="10" />

-> 설정을 위한 namespace를 추가해야한다

 

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

 

 

namespace 태그

  1. 특정한 처리기에 의해 처리 가능하도록 특정 짓기 위해 사용한다
  2. 태그의 이름을 식별하기 위해 사용한다