개발/Spring
DI (의존성 주입) 의 이해
GD_dev
2022. 3. 27. 22:34
"제어의 역전 (IoC: Inversion of Control)" 프로그램의 제어 흐름이 뒤바뀜
- 일반적: 사용자가 자신이 필요한 객체를 생성해서 사용
- IoC (제어의 역전)
- 용도에 맞게 필요한 객체를 그냥 가져다 사용
- "DI (Dependency Injection)" 혹은 한국말로 "의존성 주입"이라고 부릅니다.
- 사용할 객체가 어떻게 만들어졌는지는 알 필요 없음
- 실생활 예제) 가위의 용도별 사용
- 용도에 맞게 필요한 객체를 그냥 가져다 사용
- Repository DI 적용
public void createProduct(Product product) throws SQLException {
// DB 연결
Connection connection = DriverManager.getConnection("jdbc:h2:mem:springcoredb", "sa", "");
DI 적용하기 위해, 위에 코드를 아래로 변경.
private final String dbUrl;
private final String dbId;
private final String dbPassword;
public ProductRepository(String dbUrl, String dbId, String dbPassword){
this.dbUrl = dbUrl;
this.dbId = dbId;
this.dbPassword = dbPassword;
}
public void createProduct(Product product) throws SQLException {
// DB 연결
Connection connection = getConnection();
+
private Connection getConnection() throws SQLException {
return DriverManager.getConnection(dbUrl, dbId, dbPassword);
}
- Service DI 적용
public class ProductService {
public Product createProduct(ProductRequestDto requestDto) throws SQLException {
// 요청받은 DTO 로 DB에 저장할 객체 만들기
Product product = new Product(requestDto);
ProductRepository productRepository = new ProductRepository();
productRepository.createProduct(product);
return product;
}
위에 코드를 아래로 변경,
@Component // 아래 bean으로 관리
public class ProductService {
private final ProductRepository productRepository;
@Autowired
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
public Product createProduct(ProductRequestDto requestDto) throws SQLException {
// 요청받은 DTO 로 DB에 저장할 객체 만들기
Product product = new Product(requestDto);
productRepository.createProduct(product);
return product;
}
- Controller 또한 DI 적용
public class ProductController {
private final ProductService productService;
@Autowired
public ProductController(ProductService productService) {
this.productService = productService;
}