打印所有加载的 Spring bean

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

120718 次浏览

你可以试试打电话

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

或者打开 org.springframework的调试日志记录(在弹簧启动中,使用参数 --logging.level.org.springframework=DEBUG)

是的,联系 ApplicationContext然后打电话给 .getBeanDefinitionNames()

You can get the context by:

  • implementing ApplicationContextAware
  • injecting it with @Inject / @Autowired (after 2.5)
  • 使用 WebApplicationContextUtils.getRequiredWebApplicationContext(..)

相关: 您还可以通过注册一个 BeanPostprocessor bean 来检测每个 bean 的注册。

public class PrintBeans {
@Autowired
ApplicationContext applicationContext;


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

打印所有 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";
}
}

带有弹簧启动器和启动器

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

you can check the endpoint /beans

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

设置过程如下:

  1. 将依赖性加入等级 :

在分级文件中添加风箱:

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

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

  1. 调用/bean 端点 :

    安装完成后,弹簧将启用一些与度量相关的端点。 它的一个端点是 豆子 在调用这个端点之后,它将提供一个 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":[]}]

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

希望这个能帮到你。谢谢。)

GetBeanDefinition itionNames () 没有显示了已注册为 没有 BeanDefinition 实例的 bean。

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

正如您在输出中看到的,environment, systemProperties, systemEnvironment bean 将使用 GetBeanDefinition itionNames ()方法显示 not

弹簧靴

对于 Spring 启动 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", 「环境」, "systemProperties", 系统环境, “ org.springframework.context.annotation.interalConfigurationAnnotationProcessor”, “ org.springframework.boot.autoconfigure.interalCachingMetadataReaderFactory”, “ org.springframework.boot.autoconfigure.treaty. BeanTypeRegistry”, “ org.springframework.context.annotion. ConfigurationClassPostProcessor.import Registry”, “ properties tySourcesPlaceholderConfigrer”, “ org.springframework.boot.context.properties. ConfigurationPropertiesBindingPostProcessor.store”, “ presveErrorControllerTargetClassPostProcessor”, "org.springframework.context.annotation.internalAutowiredAnnotationProcessor", “ org.springframework.context.annotation.interalRequredAnnotationProcessor”, “ org.springframework.context.annotation.interalCommonAnnotationProcessor”, "org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor", “ org.springframework.Scheding.Annotation.ProxyAsyncConfiguration”, “ org.springframework.context.annotation.interalAsyncAnnotationProcessor”, “ methodValidationPostProcessor”, “嵌入式 ServletContainerCustomizerBeanPostProcessor”, “ errorPageRegistrarBeanPostProcessor”, “ MessageSource” “ applicationEventMulticaster”, “ org.springframework.boot.autoconfigure.web. EmbeddedServletContainerAutoConfiguration $EmbeddedTomcat”, “ tomcatEmbeddedServletContainerFactory” “ org.springframework.boot.autoconfigure.websocket. WebSocketAutoConfiguration $TomcatWebSocketConfiguration”, “ websocketContainerCustomizer” “ spring.http.coding-org. springframework.boot.autoconfigure.web. HttpEncoding ingProperties”, “ org.springframework.boot.autoconfigure.web. HttpEncode ingAutoConfiguration”, “ localeCharsetMappingsCustomizer”, "org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration", “ serverProperties” “复制服务器属性检测器”, “ spring.resources-org. springframework.boot.autoconfigure.web. ResourceProperties”, “ org.springframework.boot.autoconfigure.web. ErrorMvcAutoConfiguration $DefaultErrorViewResolverConfiguration”, "conventionErrorViewResolver", “ org.springframework.boot.autoconfigure.web. ErrorMvcAutoConfiguration”, “ errorPageCustomizer”, “ servletContext” “ contextParameter”, “ contextAttritribute”, “ 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", “调度员 Servlet” “调度员 ServletRegistry” “ requestContextFilter”, “ org.springframework.boot.autoconfigure.web. WebMvcAutoConfiguration”, "hiddenHttpMethodFilter", “ httpPutFormContentFilter”, “字符编码过滤器” “ org.springframework.context.event.interalEventListenerProcessor”, “ org.springframework.context.event.interalEventListenerFactory”, “ reportGeneratorApplication”, “ exportController”, “ exportService” “ org.springframework.boot.autoconfigure. AutoConfigurationPackages”, “ org.springframework.boot.autoconfigure.context. PropertyPlaceholderAutoConfiguration”, “ org.springframework.boot.autoconfigure.jacksonAutoConfiguration $Jackson2ObjectMapperBuilderCustomizerConfiguration”, “ spring.jackson-org. springframework.boot.autoconfigure.jacksonProperties” “ StandardJacksonObjectMapperBuilderCustomizer” “ org.springframework.boot.autoconfigure.jacksonAutoConfiguration $JacksonObjectMapperBuilderConfiguration”, “ org.springframework.boot.autoconfigure.Jackson. Jackson AutoConfiguration” “ jsonComponent 模块” “ jacksonObjectMapperBuilder” “ org.springframework.boot.autoconfigure.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.valid.ValidationAutoConfiguration”, "defaultValidator", “ org.springframework.boot.autoconfigure.web. ErrorMvcAutoConfiguration $WhitelabelErrorViewConfiguration”, “错误” “ beanNameViewResolver” 错误属性, “ basicErrorController” "org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration", “ org.springframework.boot.autoconfigure.web. WebMvcAutoConfiguration $WebMvcAutoConfigurationAdapter”, “ mvcContent 谈判管理器”, "org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration", “ stringHttpMessageConverter”, “ org.springframework.boot.autoconfigure.web. JacksonHttpMessageConvertersConfiguration $MappingJackson2HttpMessageConverterConfiguration”, "mappingJackson2HttpMessageConverter", "org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration", “信息转换器” “ mvcConversonService” “ mvcValidator” “ requestMappingHandlerAdapter”, “ mvcResourceUrlProvider” “ requestMappingHandlerMapping”, “ mvcPathMatcher” “ mvcUrlPathHelper” "viewControllerHandlerMapping", “ beanNameHandlerMapping”, “ resource HandlerMapping”, “ defaultServletHandlerMapping”, “ mvcUriComponent” “ httpRequestHandlerAdapter” “ simpleControllerHandlerAdapter” “ handlerExceptionResolver”, “ mvcViewResolver” “ org.springframework.boot.autoconfigure.web. WebMvcAutoConfiguration $WebMvcAutoConfigurationAdapter $FaviconConfiguration”, “ FaviconRequestHandler” “ FaviconHandlerMapping” “ defaultViewResolver” “视图解析器” “欢迎 PageHandlerMapping” “ org.springframework.boot.autoconfigure.jmx. JmxAutoConfiguration”, “ objectNamingStrategy” “ mbeanServer” "mbeanExporter", “ org.springframework.boot.autoconfigure.admin. SpringApplicationAdminJmxAutoConfiguration”, “ SpringApplicationAdminRegistry” “ org.springframework.boot.autoconfigure.context. ConfigurationPropertiesAutoConfiguration”, “ org.springframework.boot.autoconfigure.web. JacksonHttpMessageConvertersConfiguration”, Spring.info-org.springframework.boot.autoconfigure.info “ 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” “ HateoasObjecenesisCacheDisabler” "org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration$LiveReloadConfiguration$LiveReloadServerConfiguration", "org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration$LiveReloadConfiguration", “ optionalLiveReloadServer” “ org.springframework.boot.devtools.autoconfigure. LocalDevToolsAutoConfiguration”, “生命周期处理器” ]

下面是从 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 ******************