테스트 코드 작성
- 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: 스프링이 내부에서 사용하는 빈
※ 본 게시글은 인프런의 스프링 핵심 원리 - 기본편(김영한)을 수강하고 정리한 내용입니다.
'Study > Spring' 카테고리의 다른 글
[스프링 핵심 원리 - 기본편] 스프링 컨테이너와 스프링 빈(스프링 빈 조회 - 동일한 타입이 둘 이상) (0) | 2022.12.25 |
---|---|
[스프링 핵심 원리 - 기본편] 스프링 컨테이너와 스프링 빈(스프링 빈 조회 - 기본) (0) | 2022.12.24 |
[스프링 핵심 원리 - 기본편] 스프링 컨테이너와 스프링 빈(스프링 컨테이너 생성) (0) | 2022.12.21 |
[스프링 핵심 원리 - 기본편] 스프링 핵심 원리 이해2 - 객체 지향 원리 적용(스프링으로 전환하기) (0) | 2022.12.17 |
[스프링 핵심 원리 - 기본편] 스프링 핵심 원리 이해2 - 객체 지향 원리 적용(IoC, DI, 그리고 컨테이너) (0) | 2022.12.16 |