-
(스프링 기본) 8 - 컨테이너에 등록된 모든 빈 조회개발/Spring 2024. 10. 9. 13:27
이전 시간에 컨테이너에 등록한 빈을 Test 코드에서 조회해본다.
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
컨테이너에 등록된 모든 Bean 을 조회하기 위해서 AnnotationConfigApplicationContext 컨테이너를 만든다.
참고로 해당 컨테이너는 ApplicationContext 인터페이스 구현체로 하나의 컨테이너라 할 수 있다.
@Test @DisplayName("모든 빈 출력하기") void findAllBean() { String[] beanDefinitionNames = ac.getBeanDefinitionNames(); for (String beanDefinitionName : beanDefinitionNames) { Object bean = ac.getBean(beanDefinitionName); System.out.println("name = " + beanDefinitionName + " object = " + bean); } }
getBeanDefinitionNames 를 통해 컨테이너에 담긴 모든 빈 이름을 String 배열에 넣고, 이를 iter 반복문을 통해 출력한다.
getBean 메서드를 통해 얻은 빈 이름으로 빈 객체(인스턴스)를 조회한다.
이러면 스프링에서 등록한 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); } } }
getBeanDefinition 을 하게 되면 빈에 대한 메타 데이터 정보인데,
beanDefinition.getRole() 과 BeanDefinition.ROLE_APPLICATION 의 역할이 같은지 비교해준다.
여기서 BeanDefinition.ROLE_APPLICATION 은 스프링에서 등록한 것이 아니라,
사용자가 애플리케이션을 개발하기 위해 등록한 Bean 을 의미한다.
따라서 이렇게 되면 우리가 등록한 5개의 애플리케이션 빈만 출력할 수 있는 것이다.
※ 참고
Role ROLE_APPLICATION : 직접 등록한 애플리케이션 빈
Role ROLE_INFRASTRUCTURE : 스프링 내부에서 사용하는 빈
'개발 > Spring' 카테고리의 다른 글
(스프링 기본) 10 - 다양한 설정 형식 지원(자바코드, XML) (0) 2024.10.09 (스프링 기본) 9 - BeanFactory 와 ApplicationContext (0) 2024.10.09 (스프링 기본) 7 - 스프링 컨테이너 생성 (0) 2024.10.07 (스프링 기본) 6 - spring 으로 전환하기 (0) 2024.10.07 (스프링 기본) 5 - 객체 지향 설계와 스프링 (2) 2024.10.02