Study/Spring
[스프링 핵심 원리 - 기본편] 스프링 컨테이너와 스프링 빈(컨테이너에 등록된 모든 빈 조회)
black6765
2022. 12. 23. 23:28
테스트 코드 작성
- hello.core.beanfind 패키지에 ApplicationContextInfoTest 클래스 생성
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);
// Role ROLE_APPLICATION: 직접 등록한 애플리케이션 빈
// Role ROLE_INFRASTRUCTURE: 스프링이 내부에서 사용하는 빈
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: 스프링이 내부에서 사용하는 빈
※ 본 게시글은 인프런의 스프링 핵심 원리 - 기본편(김영한)을 수강하고 정리한 내용입니다.