🧩 Spring Bean Injection
: 스프링 컨테이너에 의해 Spring Bean Configuration File에 등록된 클래스로 객체 생성시 필드에 원하는 값 또는 객체가 저장되도록 설정하는 기능
생성자 (Constructor Injection) 또는 Setter 메소드(Setter Injection)를 이용하여 값 또는 객체를 필드에 저장
1. Constructor Injection
: constructor-arg 엘리먼트의 작성순서에 의해 매개변수 값(객체)이 전달되어 필드(객체) 초기화
- index 속성 : 생성자 매개변수에 값(객체)를 전달하기 위한 순서를 속성값으로 설정
예시
<bean class="xyz.itwill05.di.Student" id="student3">
<constructor-arg value="임꺽정" index="1"/>
<constructor-arg value="agd@itwill.xyz" index="2"/>
<constructor-arg value="2000" index="0"/>
</bean>
2. Setter Injection
: 하위 엘리먼트를 사용하여 Setter 메소드를 호출하여 필드값 변경
- property 엘리먼트 : 객체의 Setter 메소드를 호출하여 필드값을 변경하는 엘리먼트
- name 속성 : 필드값을 변경하기 위한 필드명을 속성값으로 설정 (자동완성 기능 사용 가능)
=> name 속성값으로 설정된 필드에 대한 Setter 메소드를 호출하여 필드값 변경
=> 필드에 대한 Setter 메소드가 없거나 잘못 선언된 경우 예외 발생
- value 속성 : 필드에 저장된 값을 속성값으로 설정 (값 주입)
예시
<bean class="xyz.itwill05.di.Student" id="student4">
<property name="num" value="3000"/>
<property name="email" value="jjj@itwill.xyz"/>
</bean>
3. Constructor Injection + Setter Injection 함께 사용 가능
: 생성자와 Setter 메소드를 같이 사용하여 객체 초기화 작업 가능
예시
<bean class="xyz.itwill05.di.Student" id = "student5">
<constructor-arg value="4000"/>
<constructor-arg value="일지매"/>
<property name="email" value="ert@itwill.xyz"></property>
</bean>
📃 student.properties
: 프로그램 실행시 필요한 값을 전달할 목적으로 쓰는 파일
#Student Properties
num = 5000
name = \uC77C\uC9C0\uB9E4 //일지매
email = abc@itwill.xyz
Spring containter은 XML 만 읽어 들이기 때문에 Properties 파일은 영향을 주지 못함
But, Properties 파일에 있는 값을 이용할 수 있는 방법 존재
🧩 Spring Container가 Properties 파일에 있는 값을 이용할 수 있는 방법
1. PropertyPlaceholderConfigurer 클래스 (but 버그 존재, 비권장)
: properties 파일을 제공받아 파일에 설정된 값을 Spring Bean Configuration File에서 사용할 수 있도록 제공하는 클래스
=> 객체로 등록해서 Properties에 저장된 값을 사용
1)
locations 필드에 Properties 파일의 경로를 전달하여 저장
예시 - 객체로 등록 완료 (선행)
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="xyz/itwill05/di/student.properties"/>
</bean>
2)
Properties 파일에 의해 제공되는 값은 Spring Bean Configuration File에서 ${이름} 으로 사용 가능
예시 (후행)
: Properties 파일에 의해 제공되는 값을 사용하여 객체 필드 초기화 작업
<bean class="xyz.itwill05.di.Student" id= "student6">
<property name="num" value="${num}"/>
<property name="name" value="${name}"/>
<property name="email" value="${email}"/>
</bean>
2. PropertiesSourcesPlaceholderConfigurer 클래스 (사용 권장)
: Spring 5.2 이상에서는 PropertySourcesPlaceholderConfigurer 클래스를 사용하여 Properties 파일을 제공받아 Spring Bean Configuration File에서 사용할 수 있도록 변경
예시
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations" value="xyz/itwill05/di/student.properties"/>
</bean>
📍 PropertySourcesPlaceholderConfigurer 클래스와 PropertyPlaceholderConfigurer 클래스 결과는 똑같음 !!!