Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- Database
- 상속
- string
- 문자열
- db
- 배열
- Java
- rpa
- JDBC
- Eclipse
- jsp
- html
- Oracle
- jquery
- 이클립스
- React
- Array
- Scanner
- API
- SpringBoot
- mysql
- 조건문
- Uipath
- Board
- MVC
- View
- spring
- Thymeleaf
- 자료구조
- Controller
Archives
- Today
- Total
유정잉
Spring XML 설정으로 [ Constructor DI(생성자 주입) ] 본문
Constructor DI(생성자 주입)란 객체를 생성할 때, 생성자의 매개변수로 필요한 의존성을 전달하는 방식XML에서는 <constructor-arg> 태그를 사용해서 주입할 수 있음!
1️⃣ 기본 개념: Car와 Engine의 관계
예제를 쉽게 이해하기 위해, Car 클래스가 Engine 객체를 필요로 한다고 가정
즉, Car 객체가 생성될 때 Engine 객체가 필요함 → 생성자로 Engine을 주입해야 함!
2️⃣ Java 클래스 정의
✅ Engine 클래스 (주입될 객체)
package com.example;
public class Engine {
private String type;
// 생성자 (Engine 타입을 설정하는 역할)
public Engine(String type) {
this.type = type;
}
public String getType() {
return type;
}
}
✅ Engine 객체는 type이라는 문자열을 가지며,
✅ Engine 객체를 생성할 때 생성자로 type 값을 전달받아야 함
✅ Car 클래스 (Engine을 의존성으로 가짐)
package com.example;
public class Car {
private Engine engine;
// 생성자를 통해 Engine 객체를 받음 (의존성 주입)
public Car(Engine engine) {
this.engine = engine;
}
public void showEngineType() {
System.out.println("Car engine: " + engine.getType());
}
}
✅ Car 객체는 Engine 객체가 있어야 생성될 수 있음
✅ 그래서 Car의 생성자는 Engine 타입을 매개변수로 받음!
3️⃣ XML 설정 파일 (beans.xml)
이제 Car 객체를 생성할 때, Engine 객체를 자동으로 주입하도록 XML에서 설정하자!
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Engine 객체 생성 (생성자 매개변수로 "V8 Engine" 전달) -->
<bean id="engine" class="com.example.Engine">
<constructor-arg value="V8 Engine"/>
</bean>
<!-- Car 객체 생성 (생성자의 Engine 객체 주입) -->
<bean id="car" class="com.example.Car">
<constructor-arg ref="engine"/>
</bean>
</beans>
🔍 XML 코드 설명
- <bean id="engine" class="com.example.Engine">
- Engine 객체를 생성할 때 "V8 Engine"이라는 값을 넘겨서 생성
- <bean id="car" class="com.example.Car">
- Car 객체를 생성할 때 engine 객체를 생성자 매개변수로 전달
✅ 즉, Spring이 자동으로 Engine 객체를 Car의 생성자로 넣어줌!
4️⃣ 실행 코드 (Main.java)
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
// XML 설정 파일 로드 (Spring 컨테이너 초기화)
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
// "car"라는 id를 가진 Bean 가져오기
Car car = context.getBean("car", Car.class);
// Car 객체의 메서드 실행
car.showEngineType(); // 출력: Car engine: V8 Engine
}
}
5️⃣ 실행 결과
Car engine: V8 Engine
✅ Car 객체가 생성될 때,
✅ 자동으로 Engine 객체가 생성자 매개변수로 들어가고,
✅ showEngineType()을 실행하면 엔진 타입이 출력됨!
📌 정리 (Constructor DI 핵심 개념)
객체(Bean) | Car, Engine 같은 클래스를 Bean으로 관리 |
생성자 주입 | Car의 생성자로 Engine을 전달해야 함 |
XML 설정 | <constructor-arg>를 사용해 주입 |
Spring 역할 | XML 설정을 기반으로 자동으로 객체를 생성하고 주입 |
🔥 결론
- **생성자 주입(Constructor DI)**을 사용하면, 객체가 생성될 때 필요한 의존성을 자동으로 주입할 수 있음
- XML에서 <constructor-arg>를 사용하면 Spring이 자동으로 생성자 매개변수를 채워줌
- 이 방식은 불변성을 유지할 수 있고, 필수 의존성을 강제할 수 있어 안정적인 코드 작성이 가능함
728x90
'개발자 공부 > ♡ Spring XML' 카테고리의 다른 글
@ComponentScan과 @Bean의 차이점 (0) | 2025.02.04 |
---|---|
Spring의 의존성 주입(DI) 4가지 방식 [ @Autowired, 생성자, 컬렉션, Setter ] (1) | 2025.02.03 |
Spring Bean의 라이프사이클 [ init-method와 destroy-method ] (0) | 2025.02.03 |
Spring Bean의 Scope [ singleton vs prototype ] 차이점 (0) | 2025.02.03 |
Spring Bean의 생성 시점 [ lazy-init ]의 true vs false 차이점 (0) | 2025.02.03 |