관리 메뉴

제뉴어리의 모든것

생성된 Bean 목록 가져오기 본문

Spring Boot

생성된 Bean 목록 가져오기

제뉴어리맨 2021. 1. 30. 00:45
package january.man;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.stereotype.Component;

import java.awt.desktop.AppHiddenListener;

@Component
public class SampleListener implements ApplicationListener<ApplicationStartedEvent>{


    @Autowired
    private ApplicationContext context;


    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {

        String[] allBeanNames = context.getBeanDefinitionNames();
        for (String beanName : allBeanNames) {
            System.out.println(beanName);


        }
    }
}

ApplicationListener 를 이용하여 ApplicationStartedEvent 이벤트 발생시(앱이 다 실행된뒤,그래야지 ApplicationContext도 안정적이게 만들어진 후이기때문에. Bean이 되는 클래스의 생성자에 넣으면 아직 만들어지지 않은 Bean을 뽑아내려다 Null 발생)
생성된 Bean 목록을 뽑아냄.

 

필요 없는 import도 포함 되어있음.