모음/[스프링 퀵스타트]

[스프링 퀵스타트] Day1 - chapter4. 의존성 주입 (v2024)

ttoance 2024. 10. 1. 16:40

 

Inversion of Control (IoC) in Spring Framework

Inversion of Control (IoC) is a fundamental principle in the Spring Framework. It states that the container automatically manages the creation and dependencies of objects. This allows for more modular, testable, and maintainable code. Let's break down the key concepts illustrated in the image for a detailed blog post.

핵심 개념: 제어의 역전 (Inversion of Control)

  • IoC는 스프링의 핵심 원리로, 객체의 생성 및 의존 관계를 개발자가 아닌 컨테이너가 자동으로 관리합니다. 이를 통해 결합도가 낮아지고 유연한 설계가 가능합니다.

IoC의 두 가지 구현 방법

  1. Dependency Lookup (의존성 조회)
    • 객체가 필요한 의존성을 컨테이너로부터 직접 요청하여 주입받는 방식입니다.
    • 이 방식은 컨테이너의 존재를 인식해야 하므로, 일반적으로 의존성을 주입하는 데 사용되는 다른 방법보다 선호되지 않습니다.
  2. Dependency Injection (의존성 주입)
    • 스프링 컨테이너가 객체의 의존성을 자동으로 주입하는 방식입니다.
    • 주로 두 가지 형태로 구현됩니다:
      • Setter Injection
        • Setter 메서드를 통해 의존성을 주입하는 방법입니다.
        • 선택적인 의존성이나 다수의 의존성이 필요한 경우 유용합니다.
      • Constructor Injection
        • 객체 생성 시점에 생성자를 통해 의존성을 주입하는 방법입니다.
        • 객체의 불변성을 보장하고 필수 의존성을 설정하는 데 사용됩니다.

 

setter injection 예시 

<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">

    <!-- Speaker 빈 설정 -->
    <bean id="speaker" class="Speaker"/>

    <!-- Car 빈 설정 및 의존성 주입 -->
    <bean id="car" class="Car">
        <property name="speaker" ref="speaker"/>
    </bean>
</beans>

 

construnctor injection 예시 

<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">

    <!-- Speaker 빈 설정 -->
    <bean id="speaker" class="Speaker"/>

    <!-- Car 빈 설정 및 의존성 주입 -->
    <bean id="car" class="Car">
        <constructor-arg ref="speaker"/>
    </bean>
</beans>

 

컬렉션 객체 설정 (Collection Injection)

  • 스프링에서 다양한 컬렉션 타입(List, Set, Map, Properties)에 의존성을 주입할 수 있습니다. 이는 다수의 의존성을 관리하고 설정할 때 사용됩니다.
    • List 타입 매핑: 순서가 중요한 경우에 사용합니다.
    • Set 타입 매핑: 중복이 없고 순서가 중요하지 않을 때 사용합니다.
    • Map 타입 매핑: Key-Value 형태로 의존성을 관리할 때 적합합니다.
    • Properties 타입 매핑: 속성 파일의 Key-Value 형태를 주입할 때 사용합니다.

XML 설정 예시

  • 스프링에서 의존성을 주입하는 방법 중 하나는 XML을 사용하는 것입니다. 아래 예시는 XML 설정 파일에서 의존성을 주입하는 코드 스니펫입니다.

 

 

 

결론

IoC와 의존성 주입은 스프링 프레임워크의 핵심이며, 객체 간의 의존성을 효율적으로 관리하여 애플리케이션의 유연성과 테스트 가능성을 높여줍니다. 이 원리를 잘 이해하고 적절히 활용하면, 더 유지보수하기 쉬운 코드를 작성할 수 있습니다.

반응형