如何在启动时拦截spring boot bean加载?

时间:2017-06-05 16:04:09

标签: spring-boot

我有一个使用spring boot的javafx应用程序。我想在启动画面显示正在加载的bean。

如何拦截bean加载,以便得到它的名字?

我之前曾指出它已在这里得到解答: Print all the Spring beans that are loaded

但是我想知道正在加载哪个bean,而不是已经加载的bean。

1 个答案:

答案 0 :(得分:1)

您可以使用BeanPostProcessor。初始化之前和之后将通知任何bean:

public class PrintingBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("Before init: " + beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("After init: " + beanName);
        return bean;
    }

}

要注册它,在我的配置类中我只需:

  @Bean
    public BeanPostProcessor postProcessor() {
        return new PrintingBeanPostProcessor();
    }

然后在启动时打印:

Before init: resourceHandlerMapping
After init: resourceHandlerMapping
Before init: defaultServletHandlerMapping
After init: defaultServletHandlerMapping
Before init: mvcUriComponentsContributor
After init: mvcUriComponentsContributor
Before init: httpRequestHandlerAdapter
After init: httpRequestHandlerAdapter

(这显然只是它打印的一小部分)

希望有所帮助,

阿图尔