Spring/Spring

[Spring][Core] 2-6. Bean: Autowiring Collaborators

noahkim_ 2023. 10. 14. 22:29

1. Autowiring Collaborators

Autowiring

  • 빈들 사이의 의존성을 자동으로 연결하는 기능입니다.
  • ApplicationContext 내에서 빈들의 종속성을 자동으로 매칭하여 연결해 줍니다.

 

장점
항목 설명 비고
구성의 간소화 프로퍼티나 생성자 인수를 직접 명시할 필요가 줄어듦
XML이나 Java 설정에서 코드량 감소
동적인 구성 업데이트 새로운 의존성 추가 시, 구성 변경 없이 자동 반영
코드 안정화 이후에는 명시적인 설정으로 전환 가능
개발 초기 단계에서 유용
유지보수성과 명확성 확보 목적

 

설정

모드 설명 비고
no (default) 자동 와이어링을 수행하지 않음
명시적 의존성 주입 필요
byName 프로퍼티 이름과 같은 이름의 빈을 찾아 자동 주입 이름 일치 필수
byType 프로퍼티의 타입과 일치하는 빈을 찾아 자동 주입
동일 타입 빈이 1개여야 충돌 없음
constructor 생성자 인자 타입과 일치하는 빈을 찾아 자동 주입
생성자 대상 (byType과 유사)

 

예시) 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">

    <bean id="book" class="com.example.Book" />

    <bean id="library" class="com.example.Library" autowire="byName" />
    <bean id="library" class="com.example.Library" autowire="byType" />
    <bean id="library" class="com.example.Library" autowire="constructor" />
</beans>

 

 

예시) java

더보기
더보기
@Component
public class Car {
    private Engine engine;

    // 명시적 주입 (생성자 또는 setter)
    @Autowired
    public void setEngine(Engine engine) {
        this.engine = engine;
    }
}​
public class Car {
    private Engine engine;

    // byName or byType
    public void setEngine(Engine engine) {
        this.engine = engine;
    }
}
  • xml 정의에 의해 결정됨

 

public class Car {
    private Engine engine;

    // constructor
    public Car(Engine engine) {
        this.engine = engine;
    }
}