IoC의 대표적인 구현 방식으로는 DI(Dependency Injection)과 서비스 로케이터 패턴이 있습니다. 스프링은 주로 DI 방식을 사용하여 IoC를 구현합니다.
IoC 컨테이너는 IoC 개념을 구현하는 스프링의 핵심 컴포넌트로, 객체(빈, Bean)의 생성, 관리, 의존성 주입을 담당하는 객체 생성 및 관리의 중심입니다. IoC 컨테이너는 애플리케이션이 실행되는 동안 빈을 등록하고 필요한 의존성을 주입해 주므로, 개발자는 객체의 생명 주기를 신경 쓰지 않아도 됩니다.
IoC 컨테이너는 두 가지로 나눌 수 있습니다:
graph TD
subgraph 기존 제어
A[객체 A]
B[객체 B]
A --> B
end
subgraph 제어의 역전 IoC
C[IoC 컨테이너]
C -->|의존성 주입| A2[객체 A]
C --> B2[객체 B]
A2 -->|참조| B2
end
간단한 DI와 IoC 컨테이너 예제를 통해 이해해 보겠습니다.
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
// Dependency class
@Component
public class DependencyClass {
public void serve() {
System.out.println("DependencyClass: Service is being provided.");
}
}
// Main Service class
@Component
public class MainService {
private final DependencyClass dependency;
@Autowired // Dependency Injection
public MainService(DependencyClass dependency) {
this.dependency = dependency;
}
public void performService() {
dependency.serve();
}
}
// Configuration and usage
public class IoCExample {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext("your.package.name");
MainService mainService = context.getBean(MainService.class);
mainService.performService();
}
}
ApplicationContext
가 IoC 컨테이너 역할을 하여 MainService
와 DependencyClass
객체를 생성하고, 의존성을 주입합니다.MainService
는 DependencyClass
에 의존하지만, 이를 스스로 생성하지 않고 IoC 컨테이너가 관리하여 객체 간 결합도가 낮아집니다.