打印所有已加载的Spring Bean


94

有没有办法打印所有在启动时加载的spring bean?我正在使用Spring 2.0。

Answers:


87

是的,联系ApplicationContext并致电.getBeanDefinitionNames()

您可以通过以下方式获取上下文:

  • 实施 ApplicationContextAware
  • 与注射它@Inject/ @Autowired(2.5)之后
  • WebApplicationContextUtils.getRequiredWebApplicationContext(..)

相关:您还可以通过注册BeanPostprocessorBean 来检测每个Bean的注册。它将为每个bean通知。


1
实现ApplicationContextAware接口的原因是因为Spring框架使它有机会访问应用程序上下文。您应该将其放在所需@Configuration应用程序上下文的类中。
smwikipedia


1
applicationContext.getBeanDefinitionNames()不显示没有BeanDefinition实例注册的Bean。您将无法列出手动注册的单例bean。ex- :)不能列出环境,systemProperties,systemEnvironment bean。但是,这些豆在容器中可用。您可以使用@Auwired Environment env等自动接线。 stackoverflow.com/a/54863282/1840774
Velu

66
public class PrintBeans {
    @Autowired
    ApplicationContext applicationContext;

    public void printBeans() {
        System.out.println(Arrays.asList(applicationContext.getBeanDefinitionNames()));
    }
}

applicationContext.getBeanDefinitionNames()不显示没有BeanDefinition实例注册的Bean。您将无法列出手动注册的单例bean。ex- :)不能列出环境,systemProperties,systemEnvironment bean。但是,这些豆在容器中可用。您可以使用@Auwired环境Env等自动装配他们stackoverflow.com/a/54863282/1840774
Velu

21

打印所有bean名称及其类:

package com.javahash.spring.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloWorldController {

    @Autowired
    private ApplicationContext applicationContext;

    @RequestMapping("/hello")
    public String hello(@RequestParam(value="key", required=false, defaultValue="World") String name, Model model) {

        String[] beanNames = applicationContext.getBeanDefinitionNames();

        for (String beanName : beanNames) {

            System.out.println(beanName + " : " + applicationContext.getBean(beanName).getClass().toString());
        }

        model.addAttribute("name", name);

        return "helloworld";
    }
}

1
applicationContext.getBeanDefinitionNames()不显示没有BeanDefinition实例注册的Bean。您将无法列出手动注册的单例bean。ex- :)不能列出环境,systemProperties,systemEnvironment bean。但是,这些豆在容器中可用。您可以使用@Auwired环境Env等自动装配他们stackoverflow.com/a/54863282/1840774
Velu

19

带有Spring Boot和执行器启动器

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

您可以检查端点 /beans


2
问题是针对Spring 2.0,而不是 Spring Boot。
TMN

7

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

package io.velu.core;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class Core {

public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Core.class);
    String[] singletonNames = context.getDefaultListableBeanFactory().getSingletonNames();
    for (String singleton : singletonNames) {
        System.out.println(singleton);
    }       
}

}


控制台输出

environment
systemProperties
systemEnvironment
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
messageSource
applicationEventMulticaster
lifecycleProcessor

正如您在输出中看到的那样,不会使用context.getBeanDefinitionNames()方法显示环境,systemProperties和systemEnvironment 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”,“ environment”,“ systemProperties”,“ systemEnvironment”,“ org.springframework.context.annotation.internalConfigurationAnnotationProcessor”,“ org.springframework.boot.autoconfigure。” internalCachingMetadataReaderFactory”,“ org.springframework.boot.auto.config.condition.BeanTypeRegistry”,“ org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry”,“ propertySourcesPlaceholderConfigurer”,“ org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.store” ,“prepareErrorControllerTargetClassPostProcessor“,” org.springframework.context.annotation.internalAutowiredAnnotationProcessor“,” org.springframework.context.annotation.internalRequiredAnnotationProcessor“,” org.springframework.context.annotation.internalCommonAnnotationProcessor“,” org.springframework.boot。 ConfigurationPropertiesBindingPostProcessor”,“ org.springframework.scheduling.annotation.ProxyAsyncConfiguration”,“ org.springframework.context.annotation.internalAsyncAnnotationProcessor”,“ methodValidationPostProcessor”,“ embeddedServletContainerCustomizerBeanPostProcessor”,“ errorPageRegistrarBeanPostSources”,“applicationEventMulticaster”,“ org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration $ EmbeddedTomcat”,“ tomcatEmbeddedServletContainerFactory”,“ org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration $ TomcatWebSocketConfiguration”,“ websocketContainerCustomizer”,编码“ springhttp”。 org.springframework.boot.autoconfigure.web.HttpEncodingProperties”,“ org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration”,“ localeCharsetMappingsCustomizer”,“ org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration”,“ serverProperties”,“ plicatorServerPropertiesDetector”,“ spring.resources-org.springframework.boot。autoconfigure.web.ResourceProperties”,“ org.springframework.boot.auto.config.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”,“ hiddenHttpMethod” ,“ httpPutFormContentFilter”,“ characterEncodingFilter”,“ org.springframework.context.event.internalEventListenerProcessor”,“ org.springframework.context.event.internalEventListenerFactory”,“ reportGeneratorApplication”,“ exportController”,“ exportService”,“ org.springframework”。开机。autoconfigure.AutoConfigurationPackages”,“ org.springframework.boot.auto.config.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”,“ orgspring”。 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”,“ error”,“ beanNameViewResolver”,“ errorAttributes”,“ basicErrorController” ,“ org.springframework.boot.autoconfigure.web。WebMvcAutoConfiguration $ EnableWebMvcConfiguration”,“ org.springframework.boot.auto.config.web.WebMvcAutoConfiguration $ WebMvcAutoConfigurationAdapter”,“ mvcContentNegotiationManager”,“ org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration $ StringHttpMessageConverterConfiguration”,“ stringHttpMessageConverterwork”,“ org.spring.org”。 boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration $ MappingJackson2HttpMessageConverterConfiguration”,“ mappingJackson2HttpMessageConverter”,“ org.springframework.boot.auto.config.web.HttpMessageConvertersAutoConfiguration”,“ messageConverters”,“ mvcConversionService”,“ mvcValidator”,requestMappingHandlerAdapter”,“ mvcResourceUrlProvider”,“ requestMappingHandlerMapping”,“ mvcPathMatcher”,“ mvcUrlPathHelper”,“ viewControllerHandlerMapping”,“ beanNameHandlerMapping”,“ resourceHandlerMapping”,“ defaultServletHandlerMapping”,“ mvcUriComponentsContributor”,“ httpRequestHandlerAdapterHandlerException” ,“ 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.LocalRevToolsAuto $$ Configuration org.springframework.boot.devtools.autoconfigure。LocalDevToolsAutoConfiguration $ LiveReloadConfiguration”,“ OptionalLiveReloadServer”,“ org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration”,“ lifecycleProcessor”]


6

您可以尝试致电

org.springframework.beans.factory.ListableBeanFactory.getBeansOfType(Object.class)

或打开的调试日志记录org.springframework。(在春季启动中,这是使用参数--logging.level.org.springframework=DEBUG


ListableBeanFactory是一个接口。在哪里可以得到扩展该接口的类的实例,以便执行该方法getBeansOfType或接口中的任何其他方法?我看到可以ApplicationContext扩展它,但是您的示例未显示如何获取其中之一。
ErikE

您只需添加一个字段@Autowired ListableBeanFactory listableBeanFactory,您将获得一个字段(实现类型无关紧要)
artbristol

1

使用 spring-boot-starter-actuator您可以轻松访问所有bean。

这是设置过程:

  1. 将依赖项添加到gradle中

将波纹管添加到gradle文件中:

compile("org.springframework.boot:spring-boot-starter-actuator")
  1. 在application.properties上启用安全性

添加management.security.enabled=false到您的application.property文件中

  1. 呼叫/ beans端点

    在那之后,spring将启用一些与指标相关的端点。它的端点之一是/ beans 。调用此端点后,它将提供一个json文件,其中包含您所有的bean,包括其依赖关系和作用域。

这是一个示例json文件:

[{"context":"application:8442","parent":null,"beans":[{"bean":"beanName","aliases":[],"scope":"singleton","type":"packageName$$4b46c703","resource":"null","dependencies":["environment","beanName1","beanName2"]},{"bean":"org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory","aliases":[],"scope":"singleton","type":"org.springframework.core.type.classreading.CachingMetadataReaderFactory","resource":"null","dependencies":[]}]

有关更多信息,请访问以下链接:

希望这会帮助你。谢谢 :)


1
春季!=春季靴
Himanshu Bhardwaj '18 -10-18

是的,那是真正的兄弟:)。此解决方案用于sprint引导。
萨耶杜尔·卡里姆医师

1

这是从spring应用程序上下文中打印所有bean名称的另一种方法:

import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

/***********************************************************************************************************
 * Java File: MainApplication.java
 * Description: Main class to run the application.
 * 
 ***********************************************************************************************************/

@SpringBootApplication
public class MainApplication {

private static final Logger logger = LogManager.getLogger(MainApplication.class);

public static void main(String[] args) 
{
    final ConfigurableApplicationContext context = SpringApplication.run(MainApplication.class, args);

    final AtomicInteger counter = new AtomicInteger(0);
    logger.info("**************** START: Total Bean Objects: {} ******************", context.getBeanDefinitionCount());

    Arrays.asList(context.getBeanDefinitionNames())
    .forEach(beanName -> {
        logger.info("{}) Bean Name: {} ", counter.incrementAndGet(), beanName);
    });

    logger.info("**************** END: Total Bean: {} ******************", context.getBeanDefinitionCount());
}

}


Sample Output:

2019-11-27 20:08:02.821 INFO  [main] [c.c.a.MainApplication:18] - **************** START: Total Bean Objects: 564 ****************** 
...........................
2019-11-27 20:08:02.821 INFO  [main] [c.c.a.MainApplication:22] - 460) Bean Name: mvcPathMatcher  
2019-11-27 20:08:02.821 INFO  [main] [c.c.a.MainApplication:22] - 461) Bean Name: mvcUrlPathHelper  
2019-11-27 20:08:02.821 INFO  [main] [c.c.a.MainApplication:22] - 462) Bean Name: viewControllerHandlerMapping  
2019-11-27 20:08:02.821 INFO  [main] [c.c.a.MainApplication:22] - 463) Bean Name: beanNameHandlerMapping  
2019-11-27 20:08:02.821 INFO  [main] [c.c.a.MainApplication:22] - 464) Bean Name: resourceHandlerMapping 
...........................
2019-11-27 20:08:02.821 INFO  [main] [c.c.a.MainApplication:25] - **************** END: Total Bean: 564 ****************** 
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.