Spring Container에 등록된 Bean을 조회하는 방법

Heejun Kim·2025년 4월 8일

Spring

목록 보기
4/6

스프링에서 빈을 조회하는 방식은 다양하게 있는데 공부하는 내용 기반으로 가볍게 정리했습니다.

 //스프링 컨테이너에 등록된 Configure 클래스인 AppConfig를 호출하여 가져와서 여기에 등록되어있는 내용을 확인 할 수 있다
 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

이렇게 미리 초기화 하면 AppConfig에 등록된 모든 빈들을 스프링 컨테이너에서 꺼내 쓸 수 있게 된다.

이때 중요한 점은 역할과 구현을 명확하게 구분해야 한다는 것이다.
즉, 빈을 조회할 때는 구체 클래스가 아니라 인터페이스나 추상 타입(역할)을 기준으로 조회하는 것이 바람직하다.

// 좋은 예: 역할(인터페이스) 기반으로 조회
AppleService appleService = context.getBean(AppleService.class);

// 나쁜 예: 구현 클래스에 의존
AppleServiceImpl appleService = context.getBean(AppleServiceImpl.class);

이와 같이 구체 클래스 타입으로 조회하는 방식은 유연하지 못하고, 역할과 구현의 구분이 깨지므로 권장되지 않는다.

✅ 다양한 Bean 조회 방법

1. 이름 + 타입으로 조회

Object bean = context.getBean("myService", MyService.class);

2. 타입만으로 조회

MyService bean = context.getBean(MyService.class);

3. 모든 빈 이름 출력

String[] beanNames = context.getBeanDefinitionNames();
for (String name : beanNames) {
    System.out.println("bean name = " + name);
}

4. 특정 타입에 해당하는 모든 빈 조회

Map<String, MyService> beansOfType = context.getBeansOfType(MyService.class);

마지막은 Junit5을 이용하여 빈 조회 테스트를 해보았다

@ExtendWith(SpringExtension.class)
// 테스트에 사용할 스프링 설정 클래스 지정
@ContextConfiguration(classes = AppConfig.class)
class AppleServiceTest {

    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

    @Test
    @DisplayName("이름으로 빈 조회 - appleService")
    void getBeanByName() {
    
    // 'appleService'라는 이름으로 등록된 빈을 AppleService 타입으로 조회
        AppleService service = context.getBean("appleService", AppleService.class);
        
         // 빈이 null이 아니고, 구현체가 AppleServiceImpl인지 검증
        assertThat(service).isNotNull();
        assertThat(service).isInstanceOf(AppleServiceImpl.class);
    }

    @Test
    @DisplayName("타입으로만 빈 조회 - AppleService.class")
    void getBeanByTypeOnly() {
        AppleService service = context.getBean(AppleService.class);
        assertThat(service).isNotNull();
    }

    @Test
    @DisplayName("구현 클래스로 빈 조회 - AppleServiceImpl.class")
    void getBeanByConcreteType() {
        AppleServiceImpl service = context.getBean(AppleServiceImpl.class);
        assertThat(service).isNotNull();
    }
}

0개의 댓글