티스토리 뷰

이 어플리케이션에는 몇개의 bean이 생성이 되었고 이것들은 어떤 이름을 가지고 있으며 실제 클래스는 무엇인지에 대한 정보를 원하는 경우가 있다. Spring 기동시 로그를 살펴보면 이것에 대한 정보를 얻을수도 있지만 생성된 bean의 정보를 이용하여 간단하게 구할 수 있다. 

@Autowired
DefaultListableBeanFactory beanFactory;

Bean에 대한 정보를 가지고 있는 beanFactory의 구현체인 DefaultListableBeanFactory를 주입받는다. 

그럼 이 beanFactory로부터 bean에 대한 이런 저런 정보들을 가지고 올 수 있다. 

public void beanInfo() {
    System.out.println("#### total bean count : " + beanFactory.getBeanDefinitionNames().length);
		
    for(String beanName : beanFactory.getBeanDefinitionNames()){
        System.out.println("beanName : " + beanName + 
             "\n" + "className : " + beanFactory.getBean(beanName).getClass().getName());
    }
}

그리고선 위에서 주입받은 beanFactory.getBeanDefinitionNames()를 이용해 bean의 목록을 가지고 와서 필요한 일을 수행한다.  이대로 실행을 해보면 다음과 같이 결과가 나오는것을 확인할 수 있다. 

#### total bean count : 138
beanName : org.springframework.context.annotation.internalConfigurationAnnotationProcessor
className : org.springframework.context.annotation.ConfigurationClassPostProcessor
beanName : org.springframework.context.annotation.internalAutowiredAnnotationProcessor
className : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
beanName : org.springframework.context.annotation.internalCommonAnnotationProcessor
className : org.springframework.context.annotation.CommonAnnotationBeanPostProcessor
beanName : org.springframework.context.event.internalEventListenerProcessor
className : org.springframework.context.event.EventListenerMethodProcessor
beanName : org.springframework.context.event.internalEventListenerFactory
className : org.springframework.context.event.DefaultEventListenerFactory
beanName : demoApplication
className : com.example.demo.DemoApplication$$EnhancerBySpringCGLIB$$748aa12b
...

이런식으로 application 실행시 생성된 bean의 개수 및 정보들을 확인할 수 있다. 기본적으로 spring-boot-starter-web 만 끼고 클래스 하나만 만들어서 동작시켜도 138개라는 bean이 생성이 되는것을 확인할 수 있었다. 

 

이처럼 bean 이름만 알면 다음과 같은 속성값을 가지고 올 수 있다.

beanFactory API

이를 잘 이용해서 필요한 정보를 뽑아낼 수 있다. 

 

끝!

댓글
최근에 올라온 글
최근에 달린 댓글
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31