ロードされているすべてのSpring Beanを印刷する


回答:


87

はい、ApplicationContext連絡してください.getBeanDefinitionNames()

次の方法でコンテキストを取得できます。

  • 実装 ApplicationContextAware
  • @Inject/で注入する@Autowired(2.5以降)
  • 使用する WebApplicationContextUtils.getRequiredWebApplicationContext(..)

関連:Beanを登録することにより、各Beanの登録を検出することもできBeanPostprocessorます。Beanごとに通知されます。


1
ApplicationContextAwareインターフェースを実装する理由は、Springフレームワークがアプリケーションコンテキストにアクセスする機会を与えるためです。あなたはそれを置くべき@Configurationことを意図したアプリケーションのコンテキストのためのクラス。
smwikipedia 2015年


1
applicationContext.getBeanDefinitionNames()は、BeanDefinitionインスタンスなしで登録されたBeanを表示しません。手動で登録されたシングルトンBeanをリストすることはできません。ex- :)環境、systemProperties、systemEnvironment Beanをリストすることはできません。ただし、これらのBeanはコンテナで使用できます。あなたは@Auwired環境ENVなど使用してそれらをautowireすることができます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をリストすることはできません。ただし、これらのBeanはコンテナで使用できます。あなたは@Auwired環境ENVなど使用してそれらをautowireすることができます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をリストすることはできません。ただし、これらのBeanはコンテナで使用できます。あなたは@Auwired環境ENVなど使用してそれらをautowireすることができますstackoverflow.com/a/54863282/1840774
Velu

19

スプリングブーツとアクチュエータスターター付き

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

エンドポイントを確認できます /beans


2
質問は、Spring Boot ではなく Spring 2.0に対するものでした。
TMN

7

applicationContext.getBeanDefinitionNames()は、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はcontext.getBeanDefinitionNames()メソッドを使用しても表示されません

春のブーツ

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.contextproperties ConfigurationPropertiesBindingPostProcessor "、" org.springframework.scheduling.annotation.ProxyAsyncConfiguration "、" org.springframework.context.annotation.internalAsyncAnnotationProcessor "、" methodValidationPostProcessor "、" embeddedServletContainerCustomizerBeanPostProcessor "、" errorPageRegistrarBeanProcessor "applicationEventMulticaster "、" org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration $ EmbeddedTomcat "、" tomcatEmbeddedServletContainerFactory "、" org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration $ TomcatWebSocketConfiguration "、" websocketContainerCustomizer "、" spring 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.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.spring boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration $ MappingJackson2HttpMessageConverterConfiguration "、" mappingJackson2HttpMessageConverterConfiguration "、" org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration "、" messageConverters "、" mvcConversionService "、" mvcValidator "、"requestMappingHandlerAdapter "、" mvcResourceUrlProvider "、" requestMappingHandlerMapping "、" mvcPathMatcher "、" mvcUrlPathHelper "、" viewControllerHandlerMapping "、" beanNameHandlerMapping "、" resourceHandlerMapping "、" defaultServletHandlerMapping "、" mvcUriComponentsContributor "、" Exception " 、「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 $ Live 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がそれを拡張しているのを見ますが、あなたの例はそれらの1つを取得する方法を示していません。
ErikE 2018

フィールド@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=falseapplication.propertyファイルに追加します

  1. / beansエンドポイントを呼び出します

    そのセットアップの後、Springはいくつかのメトリック関連のエンドポイントを有効にします。そのエンドポイントの1つは/ beansです。 このエンドポイントを呼び出すと、依存関係とスコープを含むすべてのBeanを含むjsonファイルが提供されます。

次に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
spring!= spring-boot
Himanshu Bhardwaj 2018年

ええ、それは本当の兄弟です:)。このソリューションはスプリントブート用です。
Ms. Sajedul Karim 2018

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 ****************** 
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.