스프링 컨테이너에 실제 스프링 빈들이 잘 등록되었는지 확인해보았다.

 

package hello.core.beanfind;

import hello.core.AppConfig;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ApplicationContextInfoTest {

    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);

    @Test
    @DisplayName("모든 빈 출력하기")
    void findAllBean(){
        String[] beanDefinitionNames = ac.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            Object bean = ac.getBean(beanDefinitionName);
            System.out.println("name = "+beanDefinitionName+" object = "+ bean);

        }
    }    @Test
    @DisplayName("애플리케이션 빈 출력하기")
    void findApplicationBean(){
        String[] beanDefinitionNames = ac.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            BeanDefinition beanDefinition = ac.getBeanDefinition(beanDefinitionName);

            if(beanDefinition.getRole() == BeanDefinition.ROLE_APPLICATION){
                Object bean = ac.getBean(beanDefinitionName);
                System.out.println("name = "+beanDefinitionName+" object = "+ bean);
            }
        }
    }



}

테스트 코드를 이용하여 찾아보았다.

 

모든 빈 출력하기

 

ac.getBeanDefinitionNames() 는 스프링에 등록된 모든 빈 이름을 조회한다.

ac.getBean() 은 빈 이름으로 빈 객체를 조회한다.

내가 직접 등록하지 않고 내부에 등록된 빈 들까지 출력해준다.

 

애플리케이션 빈 출력하기

 

스프링 내부에서 사용하는 빈은 제외하고 내가 등록한 빈만 출력할 수도 있다.

스프링이 내부에서 사용하는 빈은 getRole() 로 구분할 수 있다.

ROLE_APPLICATION 은 사용자가 정의한 빈이고

ROLE_INFRASTRUCTURE은 스프링 내부에서 사용하는 빈이다.

 

 

+ Recent posts