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

时间:2015-10-26 14:59:38

标签: spring spring-boot

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

8 个答案:

答案 0 :(得分:41)

如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。

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

答案 1 :(得分:16)

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

设置执行器

  

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

执行器中的端点列表

  

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

答案 2 :(得分:8)

嗯,虽然这个问题已经得到解答,但我仍然希望提供一个Java 8变体的答案:)

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

让我们来做Java 8 !!!

答案 3 :(得分:2)

实际上我建议除了修改@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()));

}}

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

答案 4 :(得分:2)

我为此要求做了一个小实验,找到了解决方案。我在选择诸如WEB,Actuator,HAL和Devtools之类的模块时创建了SpringBoot。我已经在应用程序属性中配置了以下属性,以加载执行器中存在的所有端点。

  

management.endpoints.web.exposure.include = *

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

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

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

enter image description here

答案 5 :(得分:2)

如@Zergleb所述,使用Actuator也是合适的,但是,根据参考文档,该端点默认不再通过“ Web”公开。因此,您需要考虑以下步骤来访问端点

  1. 将以下依赖项添加到您的pom.xml

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    
  2. 将这两个属性添加到application.properties文件中:

management.endpoints.web.exposure.include=beans

management.endpoint.beans.enabled=true

  1. 使用/actuator/beans http端点访问您的应用程序上下文Bean

答案 6 :(得分:1)

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

答案 7 :(得分:1)

applicationContext.getBeanDefinitionNames()不会显示在没有 BeanDefinition实例的情况下注册的Bean。

对于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”,      “环境”,      “系统属性”,      “ 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.jackson.JacksonAutoConfiguration $ Jackson2ObjectMapperBuilderCustomizerConfiguration”,      “ spring.jackson-org.springframework.boot.autoconfigure.jackson.JacksonProperties”,      “ standardJacksonObjectMapperBuilderCustomizer”,      “ org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration $ JacksonObjectMapperBuilderConfiguration”,      “ org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration”,      “ jsonComponentModule”,      “ jacksonObjectMapperBuilder”,      “ org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration $ JacksonObjectMapperConfiguration”,      “ jacksonObjectMapper”,      “ 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”,      “错误”,      “ 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.JacksonHttpMessageConvertersConfiguration $ MappingJackson2HttpMessageConverterConfiguration”,      “ mappingJackson2HttpMessageConverter”,      “ 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.JacksonHttpMessageConvertersConfiguration”,      “ 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”   ]

如您在输出中看到的,将使用 context.getBeanDefinitionNames()方法显示环境,systemProperties,systemEnvironment Bean。