Existe-t-il un moyen d'imprimer tous les beans de printemps chargés au démarrage? J'utilise Spring 2.0.
Existe-t-il un moyen d'imprimer tous les beans de printemps chargés au démarrage? J'utilise Spring 2.0.
Réponses:
Oui, attends ApplicationContextet appelle.getBeanDefinitionNames()
Vous pouvez obtenir le contexte en:
ApplicationContextAware@Inject/ @Autowired(après 2,5)WebApplicationContextUtils.getRequiredWebApplicationContext(..)Related: Vous pouvez également détecter l'enregistrement de chaque bean en enregistrant un BeanPostprocessorbean. Il sera notifié pour chaque grain.
public class PrintBeans {
    @Autowired
    ApplicationContext applicationContext;
    public void printBeans() {
        System.out.println(Arrays.asList(applicationContext.getBeanDefinitionNames()));
    }
}
    Imprimez tous les noms de bean et ses 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";
    }
}
    Avec Spring Boot et le démarreur de l'actionneur
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
vous pouvez vérifier le point de terminaison /beans
applicationContext.getBeanDefinitionNames () ne pas montrer les haricots qui sont enregistrés sans exemple 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
Comme vous pouvez le voir dans la sortie, les beans environment, systemProperties et systemEnvironment ne seront pas affichés à l'aide de la méthode context.getBeanDefinitionNames () .
Pour les applications Web Spring Boot, tous les beans peuvent être répertoriés à l'aide du point de terminaison ci-dessous.
@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". internalCachingMetadataReaderFactory "," org.springframework.boot.autoconfigure.condition.BeanTypeRegistry "," org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry "," propertySourcesPlaceproperties.ConfigurationProcesseur "," propertySourcesPlaceproperties.ConfigurationProcesseur "," propertySourcesPlaceproperties.ConfigurationProcesseur "," propertySourcesPlaceproperties.ConfigurationProcesseur "," propertySourcesPlaceproperties.ConfigurationProcesseur "," propertySourcesPlaceroperties.Configuration. , "préserverErrorControllerTargetClassPostProcessor "," org.springframework.context.annotation.internalAutowiredAnnotationProcessor "," org.springframework.context.annotation.internalRequiredAnnotationProcessor "," org.springframework.Processor "," org.springframe.Processor.Processeur. ConfigurationPropertiesBindingPostProcessor "," org.springframework.scheduling.annotation.ProxyAsyncConfiguration "," org.springframework.context.annotation.internalAsyncAnnotationProcessor "," methodValidationPostProcessor "," embeddedServletProcoreanProcessor "," embeddedServletProcoreanProcessor "," internalServletProcessorContainer "applicationEventMulticaster "," org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration $ EmbeddedTomcat "," tomcatEmbeddedServletContainerFactory "," org.springframework.boot.autoconfigure.websocket.Webbsocket.WebsocketCiguration.Webbsocket " org.springframework.boot.autoconfigure.web.HttpEncodingProperties "," org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration "," localeCharsetMappingsCustomizer "," org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration "," localeCharsetMappingsCustomizer "," org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration "," localeCharsetMappingsCustomizer "," org.springframework.boot.autoconfigure. duplicateServerPropertiesDetector "," spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties "," org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration $ DefaultErrorViewResolverConfiguration "," conventionErrorViewResolver "," org.springframework.boot.boot.serveur "," org.springframework.boot.figuration "," org.springframework. contextParameters "," contextAttributes "," spring.mvc-org.springframework.boot.autoconfigure.web.WebMvcProperties "," spring.http.multipart-org.springframework.boot.autoconfigure.web.MultipartProperties "," org.sprame 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", "exportController", "exportController", "exportController" démarrage.autoconfigure.AutoConfigurationPackages "," org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration "," org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration $ Jackson2ObjectMapperConfiguration. JacksonProperties "," standardJacksonObjectMapperBuilderCustomizer "," org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration $ JacksonObjectMapperBuilderConfiguration "," org.springframework.boot.autoconfigure.jackson "," org.springframework.boot.autoconfigure.jackson "," org.springframework.boot.autoconfigure.jackson "," org.springframework.boot.autoconfiguration.jackson " boot.autoconfigure.jackson.JacksonAutoConfiguration $ JacksonObjectMapperConfiguration "," jacksonObjectMapper "," org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration "," org.springframework.boot. , "org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration", "defaultValidator", "org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration $ WhitelabelErrorViewConfiguration", "basicttabelErrorViewConfiguration", "basicttabelErrorViewConfiguration", "errorReservice", "errorReserver" , "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.HttpMessage "messageVersion, vonvonversion", "messageVersionConversion", "messageVersionConversion", "messageVersionContr.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.springframeAdministration.boot. , "org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration", "org.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration", "spring.info-org.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration", "spring.info-org.springframefowork.boot. springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration "," multipartResolver "," org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration $ RestTemplateConfiguration "," restTemplateBuilder "," org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration "," spring.devtools-org.springfiguration.de "," spring.devtools-org.springfiguration.de "," spring.devtools-org.springfiguration.de "," spring.devtools-org.springfiguration.de "," spring.devtools-org.springfiguration.de "," spring.devtools-org.springfiguration.de "," spring.devtools-org.springfiguration. 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 "]
Tu pourrais essayer d'appeler
org.springframework.beans.factory.ListableBeanFactory.getBeansOfType(Object.class)
Ou activez la journalisation du débogage pour org.springframework. (Dans le démarrage du printemps, cela utilise un paramètre --logging.level.org.springframework=DEBUG)
ListableBeanFactoryest une interface. Où trouverait-on une instance d'une classe étendant cette interface afin d'exécuter la méthode getBeansOfTypeou toute autre méthode dans l'interface? Je vois que ApplicationContextcela le prolonge, mais votre exemple ne montre pas comment en acquérir un.
                    @Autowired ListableBeanFactory listableBeanFactoryet vous en aurez un (le type d'implémentation ne devrait pas avoir d'importance)
                    En utilisant, spring-boot-starter-actuatorvous pouvez facilement accéder à tous les bean.
Voici le processus de configuration:
Ajouter ci-dessous dans le fichier gradle:
compile("org.springframework.boot:spring-boot-starter-actuator")
Ajouter management.security.enabled=falsedans votre fichier application.property
point de terminaison call / beans :
Après cette configuration, le printemps activera certains points de terminaison liés aux métriques. L'un de ses points de terminaison est / beans. Après avoir appelé ces points de terminaison, il fournira un fichier json contenant tous vos bean, y compris sa dépendance et sa portée.
Voici un exemple de fichier 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":[]}]
Pour plus d'informations, visitez les liens ci-dessous:
J'espère que ceci vous aidera. Merci :)
Voici une autre façon d'imprimer tous les noms de bean à partir du contexte de l'application Spring:
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 ****************** 
    
ApplicationContextAwareinterface est que le framework Spring lui donne la possibilité d'accéder au contexte de l'application. Vous devez le placer dans la@Configurationclasse du contexte d'application prévu.