122

Is there a way to print all the spring beans that are loaded on startup?I am using Spring 2.0.

Punter Vicky
  • 15,954
  • 56
  • 188
  • 315

8 Answers8

106

Yes, get ahold of ApplicationContext and call .getBeanDefinitionNames()

You can get the context by:

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

Related: You can also detect each bean's registration by registering a BeanPostprocessor bean. It will be notified for each bean.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 2
    The reason to implement `ApplicationContextAware` interface is because Spring framework give it the *chance* to access the application context. You should place it in the `@Configuration` class for the intended application context. – smwikipedia Nov 03 '15 at 08:52
  • A related link: http://stackoverflow.com/questions/14829258/how-can-i-get-a-list-of-instantiated-beans-from-spring – smwikipedia Nov 03 '15 at 08:53
  • 3
    applicationContext.getBeanDefinitionNames() does not show the beans which are registered without BeanDefinition instance. You will not be able to list singleton beans which are registered manually. ex-:) you can not list environment, systemProperties,systemEnvironment beans. However these beans are available in the container. You can autowire them using @Auwired Environment env etc. https://stackoverflow.com/a/54863282/1840774 – Velu Feb 25 '19 at 10:00
76
public class PrintBeans {
    @Autowired
    ApplicationContext applicationContext;

    public void printBeans() {
        System.out.println(Arrays.asList(applicationContext.getBeanDefinitionNames()));
    }
}
Akceptor
  • 1,914
  • 3
  • 26
  • 31
  • 3
    applicationContext.getBeanDefinitionNames() does not show the beans which are registered without BeanDefinition instance. You will not be able to list singleton beans which are registered manually. ex-:) you can not list environment, systemProperties,systemEnvironment beans. However these beans are available in the container. You can autowire them using @Auwired Environment env etc. https://stackoverflow.com/a/54863282/1840774 – Velu Feb 25 '19 at 09:59
  • Does this work in a OSGi environment? – Diego Ramos Aug 22 '22 at 15:19
25

With Spring Boot and the actuator starter

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

you can check the endpoint /beans

moffeltje
  • 4,521
  • 4
  • 33
  • 57
vietnem
  • 317
  • 4
  • 10
22

Print all bean names and its classes:

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";
    }
}
vanfgh
  • 221
  • 2
  • 2
  • 1
    applicationContext.getBeanDefinitionNames() does not show the beans which are registered without BeanDefinition instance. You will not be able to list singleton beans which are registered manually. ex-:) you can not list environment, systemProperties,systemEnvironment beans. However these beans are available in the container. You can autowire them using @Auwired Environment env etc. https://stackoverflow.com/a/54863282/1840774 – Velu Feb 25 '19 at 09:56
14

applicationContext.getBeanDefinitionNames() does not show the beans which are registered without BeanDefinition instance.

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

Console Output

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

As you can see in the output, environment, systemProperties, systemEnvironment beans will not be shown using context.getBeanDefinitionNames() method.

Spring Boot

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

@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.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",
   "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.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"
]
Benjamin Buch
  • 4,752
  • 7
  • 28
  • 51
Velu
  • 1,681
  • 1
  • 22
  • 26
  • To note that `context` is not closed in your code and should be created inside a try-with-resouces statement. `try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext ())` – Navigatron Sep 21 '21 at 08:46
8

You could try calling

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

Or turn on debug logging for org.springframework. (In spring boot, that's using a parameter --logging.level.org.springframework=DEBUG)

artbristol
  • 32,010
  • 5
  • 70
  • 103
  • `ListableBeanFactory` is an interface. Where would one get an instance of a class extending that interface in order to execute the method `getBeansOfType` or any other method in the interface? I see that `ApplicationContext` extends it, but your example doesn't show how to acquire one of those. – ErikE Jul 15 '18 at 00:04
  • You can just add a field `@Autowired ListableBeanFactory listableBeanFactory` and you'll get one (the implementation type shouldn't matter) – artbristol Jul 15 '18 at 18:18
  • I found the bean registrations at: org.springframework.beans.factory.support.DefaultListableBeanFactory: debug This shows beans like this: 2021-08-23T17:30:36.547Z DEBUG 5255 --- [ restartedMain] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'apacheHttpClientBuilder' – Bryan Pugh Aug 23 '21 at 17:31
5

Here is another way to print all the bean names from the spring application context:

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 ****************** 
Ved Singh
  • 705
  • 9
  • 4
1

Using spring-boot-starter-actuator you can easily access all bean.

Here is the setup process:

  1. Add dependency into gradle:

Add bellow into gradle file:

compile("org.springframework.boot:spring-boot-starter-actuator")
  1. Enable security on application.properties:

Add management.security.enabled=false into your application.property file

  1. call /beans endpoint:

    After that setup spring will enable some metrics related endpoints. One of its endpoint is /beans After calling this endpoints it will provide a json file that contains all of your bean including it's dependency and scope.

Here is an example json file:

[{"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":[]}]

For more info visit bellow links:

Hope this will help you. Thanks :)

Md. Sajedul Karim
  • 6,749
  • 3
  • 61
  • 87