打印所有加载的 Spring bean - Spring Boot

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33348937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:50:58  来源:igfitidea点击:

Print all the Spring beans that are loaded - Spring Boot

springspring-boot

提问by Punter Vicky

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 应用程序一部分加载的所有 bean 的名称?我希望在 main 方法中有一些代码来打印服务器启动后加载的 bean 的详细信息。

回答by Yannic Klem

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

如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);
      }
    };
  }    
}

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

正如@Velu在评论中提到的,这不会列出手动注册的 bean。

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 notbe returned by getSingletonNames().

如果您想这样做,可以使用getSingletonNames()。不过要小心。此方法仅返回已实例化的 bean。如果 bean 尚未实例化,它将不会由 返回getSingletonNames()

回答by Zergleb

May I suggest using Actuator? it provides several endpoints including /beanswhich lists all beans in the application. You say "once the server is started" so this is an option for web applications.

我可以建议使用执行器吗?它提供了几个端点,包括/beans列出应用程序中的所有 bean。您说“一旦服务器启动”,这是 Web 应用程序的一个选项。

To set up actuator

设置执行器

https://spring.io/guides/gs/actuator-service/

https://spring.io/guides/gs/actuator-service/

List of endpoints in actuator

执行器中的端点列表

http://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html

http://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html

回答by zikzakHyman

Well, Although, this question is already answered, I still want to provide an answer which is a Java 8 variant :)

好吧,虽然这个问题已经回答了,但我仍然想提供一个 Java 8 变体的答案:)

Arrays.asList(context.getBeanDefinitionNames()).stream().sorted().forEach(System.out::println);

Lets do Java 8 !!!

让我们做 Java 8 吧!!!

回答by jfzr

Actually I would recommend to create this class aside from modifying your @SpringBootApplication.

实际上,除了修改您的@SpringBootApplication 之外,我还建议创建此类。

@Component
public class ContextTeller implements CommandLineRunner {

@Autowired
ApplicationContext applicationContext;

@Override
public void run(String... args) throws Exception {
    System.out.println("-------------> just checking!");

        System.out.println(Arrays.asList(applicationContext.getBeanDefinitionNames()));

}}

This way Spring Boot will load this class and execute just after loading context. Then you just can remove the file, and everything is clear.

这样 Spring Boot 将加载这个类并在加载上下文后立即执行。然后你就可以删除文件了,一切都清楚了。

回答by Velu

applicationContext.getBeanDefinitionNames()does notshow the beans which are registered withoutBeanDefinition instance.

applicationContext.getBeanDefinitionNames()没有显示其注册的豆子没有的BeanDefinition实例。

For spring boot web applications, all the beans can be listed using the below endpoint.

对于 Spring Boot Web 应用程序,可以使用以下端点列出所有 bean。

@RestController
@RequestMapping("/list")
class ExportController {

@Autowired
private ApplicationContext applicationContext;

@GetMapping("/beans")
@ResponseStatus(value = HttpStatus.OK)
String[] registeredBeans() {
    return printBeans();
}

private String[] printBeans() {
    AutowireCapableBeanFactory autowireCapableBeanFactory = applicationContext.getAutowireCapableBeanFactory();
    if (autowireCapableBeanFactory instanceof SingletonBeanRegistry) {
        String[] singletonNames = ((SingletonBeanRegistry) autowireCapableBeanFactory).getSingletonNames();
        for (String singleton : singletonNames) {
            System.out.println(singleton);
        }
        return singletonNames;
    }
    return null;
}

}

}



[ "autoConfigurationReport", "springApplicationArguments", "springBootBanner", "springBootLoggingSystem", "environment", "systemProperties", "systemEnvironment", "org.springframework.context.annotation.internalConfigurationAnnotationProcessor", "org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory", "org.springframework.boot.autoconfigure.condition.BeanTypeRegistry", "org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry", "propertySourcesPlaceholderConfigurer", "org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.store", "preserveErrorControllerTargetClassPostProcessor", "org.springframework.context.annotation.internalAutowiredAnnotationProcessor", "org.springframework.context.annotation.internalRequiredAnnotationProcessor", "org.springframework.context.annotation.internalCommonAnnotationProcessor", "org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor", "org.springframework.scheduling.annotation.ProxyAsyncConfiguration", "org.springframework.context.annotation.internalAsyncAnnotationProcessor", "methodValidationPostProcessor", "embeddedServletContainerCustomizerBeanPostProcessor", "errorPageRegistrarBeanPostProcessor", "messageSource", "applicationEventMulticaster", "org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat", "tomcatEmbeddedServletContainerFactory", "org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration$TomcatWebSocketConfiguration", "websocketContainerCustomizer", "spring.http.encoding-org.springframework.boot.autoconfigure.web.HttpEncodingProperties", "org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration", "localeCharsetMappingsCustomizer", "org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration", "serverProperties", "duplicateServerPropertiesDetector", "spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties", "org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration", "conventionErrorViewResolver", "org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration", "errorPageCustomizer", "servletContext", "contextParameters", "contextAttributes", "spring.mvc-org.springframework.boot.autoconfigure.web.WebMvcProperties", "spring.http.multipart-org.springframework.boot.autoconfigure.web.MultipartProperties", "org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration", "multipartConfigElement", "org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration$DispatcherServletRegistrationConfiguration", "org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration$DispatcherServletConfiguration", "dispatcherServlet", "dispatcherServletRegistration", "requestContextFilter", "org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration", "hiddenHttpMethodFilter", "httpPutFormContentFilter", "characterEncodingFilter", "org.springframework.context.event.internalEventListenerProcessor", "org.springframework.context.event.internalEventListenerFactory", "reportGeneratorApplication", "exportController", "exportService", "org.springframework.boot.autoconfigure.AutoConfigurationPackages", "org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration", "org.springframework.boot.autoconfigure.Hymanson.HymansonAutoConfiguration$Hymanson2ObjectMapperBuilderCustomizerConfiguration", "spring.Hymanson-org.springframework.boot.autoconfigure.Hymanson.HymansonProperties", "standardHymansonObjectMapperBuilderCustomizer", "org.springframework.boot.autoconfigure.Hymanson.HymansonAutoConfiguration$HymansonObjectMapperBuilderConfiguration", "org.springframework.boot.autoconfigure.Hymanson.HymansonAutoConfiguration", "jsonComponentModule", "HymansonObjectMapperBuilder", "org.springframework.boot.autoconfigure.Hymanson.HymansonAutoConfiguration$HymansonObjectMapperConfiguration", "HymansonObjectMapper", "org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration", "org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration", "org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration", "org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration", "defaultValidator", "org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration", "error", "beanNameViewResolver", "errorAttributes", "basicErrorController", "org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration", "org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter", "mvcContentNegotiationManager", "org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration", "stringHttpMessageConverter", "org.springframework.boot.autoconfigure.web.HymansonHttpMessageConvertersConfiguration$MappingHymanson2HttpMessageConverterConfiguration", "mappingHymanson2HttpMessageConverter", "org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration", "messageConverters", "mvcConversionService", "mvcValidator", "requestMappingHandlerAdapter", "mvcResourceUrlProvider", "requestMappingHandlerMapping", "mvcPathMatcher", "mvcUrlPathHelper", "viewControllerHandlerMapping", "beanNameHandlerMapping", "resourceHandlerMapping", "defaultServletHandlerMapping", "mvcUriComponentsContributor", "httpRequestHandlerAdapter", "simpleControllerHandlerAdapter", "handlerExceptionResolver", "mvcViewResolver", "org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter$FaviconConfiguration", "faviconRequestHandler", "faviconHandlerMapping", "defaultViewResolver", "viewResolver", "welcomePageHandlerMapping", "org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration", "objectNamingStrategy", "mbeanServer", "mbeanExporter", "org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration", "springApplicationAdminRegistrar", "org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration", "org.springframework.boot.autoconfigure.web.HymansonHttpMessageConvertersConfiguration", "spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties", "org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration", "multipartResolver", "org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration$RestTemplateConfiguration", "restTemplateBuilder", "org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration", "spring.devtools-org.springframework.boot.devtools.autoconfigure.DevToolsProperties", "org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration$RestartConfiguration", "fileSystemWatcherFactory", "classPathRestartStrategy", "classPathFileSystemWatcher", "hateoasObjenesisCacheDisabler", "org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration$LiveReloadConfiguration$LiveReloadServerConfiguration", "org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration$LiveReloadConfiguration", "optionalLiveReloadServer", "org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration", "lifecycleProcessor" ]

[“autoConfigurationReport”、“springApplicationArguments”、“springBootBanner”、“springBootLoggingSystem”、“environment”、“systemProperties”、“systemEnvironment”、“org.springframework.context.annotation.internalConfigurationAnnotationProcessor”、“org.springframework.boot.autoconfigure. internalCachingMetadataReaderFactory”、“org.springframework.boot.autoconfigure.condition.BeanTypeRegistry”、“org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry”、“propertySourcesPlaceholderConfigurer”、“org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.store” ,”preserveErrorControllerTargetClassPostProcessor", "org.springframework.context.annotation.internalAutowiredAnnotationProcessor", "org.springframework.context.annotation.internalRequiredAnnotationProcessor", "org.springframework.context.annotation.internalCommonAnnotationProcessor", "org.springframework.bootties.context.context.context.annotation.internalRequiredAnnotationProcessor" ConfigurationPropertiesBindingPostProcessor”、“org.springframework.scheduling.annotation.ProxyAsyncConfiguration”、“org.springframework.context.annotation.internalAsyncAnnotationProcessor”、“methodValidationPostProcessor”、“embeddedServletContainerCustomizerBeanPostProcessor”、“errorPageRegistrarBeanPostProcessor”、“messageSource”applicationEventMulticaster", "org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat", "tomcatEmbeddedServletContainerFactory", "org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration$TomcatWebSocketConfiguration", "websocketContainerCustomizer", "spring.http.encoding- org.springframework.boot.autoconfigure.web.HttpEncodingProperties”、“org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration”、“localeCharsetMappingsCustomizer”、“org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration”、“serverProperties”、“ duplicateServerPropertiesDetector", "spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties", "org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration", "conventionErrorViewResolver", "org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration", "errorPageCustomizer", "servletContext", " contextParameters”、“contextAttributes”、“spring.mvc-org.springframework.boot.autoconfigure.web.WebMvcProperties”、“spring.http.multipart-org.springframework.boot.autoconfigure.web.MultipartProperties”、“org.springframework. boot.autoconfigure.web.MultipartAutoConfiguration”、“multipartConfigElement”、“org.springframework.boot.autoconfigure.web。DispatcherServletAutoConfiguration$DispatcherServletRegistrationConfiguration", "org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration$DispatcherServletConfiguration", "dispatcherServlet", "dispatcherServletRegistration", "requestContextFilter", "org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration", "hiddenHttpMethodFilter" , "httpPutFormContentFilter", "characterEncodingFilter", "org.springframework.context.event.internalEventListenerProcessor", "org.springframework.context.event.internalEventListenerFactory", "reportGeneratorApplication", "exportController", "exportService", "org.springframework.引导。autoconfigure.AutoConfigurationPackages”、“org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration”、“org.springframework.boot.autoconfigure.Hymanson.HymansonAutoConfiguration$Hymanson2ObjectMapperBuilderCustomizerConfiguration”、“spring.Hymanson-org.springframework.boot.autoconfigure.Hymanson. HymansonProperties”、“standardHymansonObjectMapperBuilderCustomizer”、“org.springframework.boot.autoconfigure.Hymanson.HymansonAutoConfiguration$HymansonObjectMapperBuilderConfiguration”、“org.springframework.boot.autoconfigure.Hymanson.HymansonAutoConfiguration”、“jsonComponentModule”、“HymansonObjectMapperBuilder”、“org.springframework” boot.autoconfigure.Hymanson。HymansonAutoConfiguration$HymansonObjectMapperConfiguration”、“HymansonObjectMapper”、“org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration”、“org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration”、“org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration” , "org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration", "defaultValidator", "org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration", "error", "beanNameViewResolver", "errorAttributes", "basicErrorController" , "org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration"、"org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter"、"mvcContentNegotiationManager"、"org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration"、"stringHttpMessageConverter"、"org.springframework boot.autoconfigure.web.HymansonHttpMessageConvertersConfiguration$MappingHymanson2HttpMessageConverterConfiguration”、“mappingHymanson2HttpMessageConverter”、“org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration”、“messageConverters”、“mvcConversionService”、“mvcValidator”、“requestMappingHandlerAdapter”、“mvcResourceUrlProvider”、“requestMappingHandlerMapping”、“mvcPathMatcher”、“mvcUrlPathHelper”、“viewControllerHandlerMapping”、“beanNameHandlerMapping”、“resourceHandlerMapping”、“defaultServletHandlerMapping”、“mvcUriComponentsContributor”、“httpRequestHandlerException”、“simpleControllerHandlerAdapter” , "mvcViewResolver", "org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter$FaviconConfiguration", "faviconRequestHandler", "faviconHandlerMapping", "defaultViewResolver", "viewResolver”、“welcomePageHandlerMapping”、“org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration”、“objectNamingStrategy”、“mbeanServer”、“mbeanExporter”、“org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration”、“springApplicationAdminRegistrar” , "org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration", "org.springframework.boot.autoconfigure.web.HymansonHttpMessageConvertersConfiguration", "spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties", "org. springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration”、“multipartResolver”、“org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration$RestTemplateConfiguration", "restTemplateBuilder", "org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration", "spring.devtools-org.springframework.boot.devtools.autoconfigure.DevToolsProperties", " org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration$RestartConfiguration”、“fileSystemWatcherFactory”、“classPathRestartStrategy”、“classPathFileSystemWatcher”、“hateoasObjenesisCacheDisabler”、“org.springframework.boot.devtools.autoconfigure.LocalDevloadToolsAutoConfiguration$LiveReloadServer” org.springframework.boot.devtools.autoconfigure。LocalDevToolsAutoConfiguration$LiveReloadConfiguration”、“optionalLiveReloadServer”、“org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration”、“lifecycleProcessor”]

As you can see in the output, environment, systemProperties, systemEnvironmentbeans will notbe shown using context.getBeanDefinitionNames()method.

正如您在输出中看到的那样,环境、systemProperties、systemEnvironmentbean 将不会使用context.getBeanDefinitionNames()方法显示。

回答by ZIA

@Component
public class ContextTeller implements CommandLineRunner {

    @Autowired
    public ApplicationContext applicationContext;

    @Override
    public void run(String... args) throws Exception {
        System.out.println("<------------- Beans loaded --------------->");
Arrays.asList(applicationContext.getBeanDefinitionNames()).stream().forEach(System.out::println);
    }
}

回答by Nallamachu

I did one small experiment for this requirement and found this solution. I have created SpringBoot while selecting the modules like WEB, Actuator, HAL and Devtools. I have configured the below property in application properties to load all the endpoints present in actuator.

我针对这个需求做了一个小实验,找到了这个解决方案。我在选择 WEB、Actuator、HAL 和 Devtools 等模块时创建了 SpringBoot。我在应用程序属性中配置了以下属性以加载执行器中存在的所有端点。

management.endpoints.web.exposure.include=*

management.endpoints.web.exposure.include=*

You can see actuator information in, http://localhost:8080/actuator. This will show all the application information along with actuator, status, info,etc.. In that, you can find the http://localhost:8080/actuator/beanswhich will load all the beans internally created by springboot application.

您可以在http://localhost:8080/actuator 中查看执行器信息。这将显示所有应用程序信息以及执行器、状态、信息等。在其中,您可以找到http://localhost:8080/actuator/beans,它将加载 springboot 应用程序内部创建的所有 bean。

Once you are able to see all the beans information, I think it's not necessary to print again in main class.

一旦你能够看到所有的bean信息,我认为没有必要在主类中再次打印。

Since, I have already configured rest-hal-browser dependency in my application, when I load the URL of http://localhost:8080, will load the UI to search for different endpoints. In the below image I am searching for actuator information.

因为,我已经在我的应用程序中配置了 rest-hal-browser 依赖项,当我加载http://localhost:8080的 URL 时,将加载 UI 以搜索不同的端点。在下图中,我正在搜索执行器信息。

enter image description here

在此处输入图片说明