打印所有已加载的Spring Bean-Spring Boot [英] Print all the Spring beans that are loaded - Spring Boot

查看:300
本文介绍了打印所有已加载的Spring Bean-Spring Boot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何知道作为Spring Boot应用程序一部分加载的所有bean的名称?我想在main方法中有一些代码来打印服务器启动后加载的bean的详细信息.

How can I get to know names of all the beans that are loaded as part of my spring boot app? I would like have some code in main method to print the details of beans that are loaded once the server is started up.

推荐答案

如spring-boot入门指南中所示:

As shown in the getting started guide of spring-boot: https://spring.io/guides/gs/spring-boot/

@SpringBootApplication
public class Application {

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

  @Bean
  public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
    return args -> {

      System.out.println("Let's inspect the beans provided by Spring Boot:");

      String[] beanNames = ctx.getBeanDefinitionNames();
      Arrays.sort(beanNames);
      for (String beanName : beanNames) {
        System.out.println(beanName);
      }
    };
  }    
}

作为 @Velu 注释中提到的内容,它将不会列出手动注册的bean.

As @Velu mentioned in the comments, this will not list manually registered beans.

如果要这样做,可以使用

In case you want to do so, you can use getSingletonNames(). But be careful. This method only returns already instantiated beans. If a bean isn't already instantiated, it will not be returned by getSingletonNames().

这篇关于打印所有已加载的Spring Bean-Spring Boot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆