1. 의존성이란?
DI에서 의존성이란 한 객체가 다른 객체의 기능에 의존하는 관계를 의미합니다. 예를 들어, 자동차(Car) 객체가 엔진(Engine) 객체의 기능을 사용한다면, 자동차 객체는 엔진 객체에 의존하고 있다고 할 수 있습니다.
2. 의존성 주입(Dependency Injection, DI)이란?
의존성 주입은 한 객체가 다른 객체에 의존할 때, 이 의존성을 외부에서 주입하는 기법ㄱ을 말합니다. 이 기법을 사용하면 객체는 필요한 의존성을 직접 관리하지 않고, 외부에서 주입받아 사용할 수 있습니다. 이로 인해 객체는 의존성에 대해 더 이상 알 필요가 없습니다.
3. DI의 장점
DI의 가장 큰 장점은 코드의 결합도를 낮추고, 유연성을 높인다는 것입니다. 객체가 직접 의존성을 생성하거나 찾지 않기 때문에, 코드 간의 결합도가 낮아져서 코드의 유연성이 높아집니다. 따라서 코드의 변경이나 확장이 쉬워집니다. 또한, 테스트가 용이해집니다. 테스트 시에는 실제 객체 대신 모의 객체(Mock Object)를 주입할 수 있기 때문입니다.
4. DI 예시
DI를 적용하지 않은 예시)
class Engine {
void run() {
System.out.println("Engine is running...");
}
}
class Car {
private Engine engine;
Car() {
engine = new Engine(); // Car 클래스 내부에서 직접 Engine 객체를 생성
}
void start() {
engine.run(); // Engine 객체의 메서드를 호출
}
}
● Car는 직접 Engine 객체를 생성하고, Engine의 run 메서드를 호출합니다.
● 위의 코드에서 Car 클래스는 Engine 클래스에 의존하고 있습니다.
DI를 적용한 예시)
class Engine {
void run() {
System.out.println("Engine is running...");
}
}
class Car {
private Engine engine;
Car(Engine engine) { // 생성자를 통해 Engine 객체를 주입받음(의존성 주입)
this.engine = engine;
}
void start() {
engine.run(); // 주입받은 Engine 객체의 메서드를 호출
}
}
● 이 코드에서는 Car의 생성자를 통해 Engine 객체를 주입받습니다.
● 이렇게 하면, Car는 Engine 객체의 생성을 외부로 분리시킬 수 있습니다.
● 의존성을 외부에서 주입하는 방식이 바로 Dependency Injection입니다.
구분 | DI 적용하지 않은 예 | DI 적용 예 |
의존성 | 클래스 간에 직접 연결 |
인터페이스를 통해 연결
|
객체 생성 | 클래스 내에서 직접 생성 |
외부에서 생성 및 주입
|
결합도 | 높음 | 낮음 |
테스트 용이 | 어려움 | 용이 |
코드 간결화 | 낮음 | 높음 |
변경 용이 | 어려움 | 용이 |
'Spring > Spring' 카테고리의 다른 글
[Spring] Bean이란? (0) | 2024.03.05 |
---|---|
[Spring] IoC, DIP, DI란? (0) | 2024.03.05 |
[Spring] 싱글톤 패턴(Singleton pattern) (0) | 2024.02.05 |
[Spring] 한글 인코딩 에러 해결(한글 ➡️ ??) (0) | 2024.02.03 |
[Spring] 스프링과 스프링부트 (0) | 2024.01.09 |