JAVA/Spring

스프링 빈 조회: 부모 타입과 Object 타입의 차이점

min민 2024. 12. 16.

스프링 빈 조회: 부모 타입과 Object 타입의 차이점

스프링 프레임워크에서 빈(Bean)을 조회할 때 부모 타입과 Object 타입으로 조회하는 경우가 있다. 이 두 가지 방식 모두 빈의 타입 계층에 따라 결과가 달라지므로 이를 정확히 이해해야 스프링 애플리케이션을 효과적으로 관리할 수 있다.

 

 

1. 부모 타입으로 빈 조회

부모 타입으로 빈을 조회하면 해당 부모 타입과 그 자식 타입까지 조회된다. 즉, 부모 타입을 상속받거나 구현한 모든 빈이 조회 대상이 된다.

 

@Configuration
class AppConfig {
    @Bean
    public ParentBean childBean1() {
        return new ChildBean1();
    }
    
    @Bean
    public ParentBean childBean2() {
        return new ChildBean2();
    }
    
    @Bean
    public ParentBean childBean3() {
        return new ChildBean3();
    }
    
    @Bean
    public String sampleBean() {
        return "Test Bean";
    }
}

interface ParentBean {}

class ChildBean1 implements ParentBean {}
class ChildBean2 implements ParentBean {}
class ChildBean3 implements ParentBean {}

 

위 설정을 기준으로 ParentBean 타입으로 조회할 경우 다음과 같이 동작한다.

 

조회 코드

ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Map<String, ParentBean> beans = context.getBeansOfType(ParentBean.class);

beans.forEach((name, bean) -> 
    System.out.println("Bean name: " + name + ", Bean type: " + bean.getClass().getSimpleName())
);

 

출력 결과

Bean name: childBean1, Bean type: ChildBean1
Bean name: childBean2, Bean type: ChildBean2
Bean name: childBean3, Bean type: ChildBean3

 

설명:

  • ParentBean 타입으로 조회했기 때문에 ParentBean을 구현한 모든 빈이 반환되었다.
  • childBean1, childBean2, childBean3이 조회 대상이다.
  • String 타입의 sampleBean은 ParentBean을 구현하지 않았기 때문에 제외된다.

 

2. Object 타입으로 빈 조회

Object 타입으로 빈을 조회하면 스프링 컨테이너에 등록된 모든 빈이 조회된다. Object는 자바의 최상위 타입이므로 모든 빈이 포함된다.

조회 코드

ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Map<String, Object> beans = context.getBeansOfType(Object.class);

beans.forEach((name, bean) -> 
    System.out.println("Bean name: " + name + ", Bean type: " + bean.getClass().getSimpleName())
);

 

출력 결과

Bean name: childBean1, Bean type: ChildBean1
Bean name: childBean2, Bean type: ChildBean2
Bean name: childBean3, Bean type: ChildBean3
Bean name: sampleBean, Bean type: String

 

설명:

  • Object 타입으로 조회했기 때문에 모든 빈이 반환된다.
  • ParentBean과 관계없는 sampleBean(String 타입)도 포함된다.
조회 타입 반환 대상
부모 타입 (예: ParentBean) 해당 타입 및 자식 타입의 빈만 반환
Object 타입 스프링 컨테이너에 등록된 모든 빈 반환

 

 

4. 주의사항

  1. 동일 타입의 빈이 여러 개일 경우:
    특정 타입으로 조회할 때 동일한 타입의 빈이 여러 개 존재하면 예외가 발생할 수 있다. 이를 해결하려면 getBeansOfType()을 사용해 Map 형태로 반환받거나, 빈 이름을 명시적으로 지정해야 한다.
  2. 빈 이름으로 조회:
    타입 대신 이름으로 조회하는 방법도 있다.
Object bean = context.getBean("childBean1");

 

3. Object 타입 남용 주의:
Object 타입으로 빈을 조회하는 것은 범위가 너무 넓어 실무에서는 권장되지 않는다. 필요 시 명확한 타입을 기준으로 조회하는 것이 좋다.

 

총 정리

스프링 빈을 조회할 때 부모 타입으로 조회하면 그 타입의 하위 타입 빈들만 반환되고, Object 타입으로 조회하면 모든 빈이 반환된다. 빈 조회 시 요구사항에 따라 적절한 타입을 사용해야 하며, 특히 Object 타입으로 조회하는 경우 주의가 필요하다.

댓글