Imprime todos los frijoles Spring que están cargados


95

¿Hay alguna manera de imprimir todos los frijoles de primavera que se cargan al inicio? Estoy usando Spring 2.0.

Respuestas:


88

Sí, contacta ApplicationContexty llama.getBeanDefinitionNames()

Puede obtener el contexto mediante:

  • implementar ApplicationContextAware
  • inyectándolo con @Inject/ @Autowired(después de 2.5)
  • utilizar WebApplicationContextUtils.getRequiredWebApplicationContext(..)

Relacionado: también puede detectar el registro de cada bean registrando un BeanPostprocessorbean. Se notificará para cada bean.


1
La razón para implementar la ApplicationContextAwareinterfaz es porque Spring Framework le da la oportunidad de acceder al contexto de la aplicación. Debe colocarlo en la @Configurationclase para el contexto de aplicación previsto.
smwikipedia


1
applicationContext.getBeanDefinitionNames () no muestra los beans que están registrados sin la instancia de BeanDefinition. No podrá enumerar los beans singleton que se registran manualmente. ex- :) no puede enumerar los beans de entorno, systemProperties, systemEnvironment. Sin embargo, estos frijoles están disponibles en el contenedor. Puede conectarlos automáticamente usando @Auwired Environment env, etc. stackoverflow.com/a/54863282/1840774
Velu

67
public class PrintBeans {
    @Autowired
    ApplicationContext applicationContext;

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

applicationContext.getBeanDefinitionNames () no muestra los beans que están registrados sin la instancia de BeanDefinition. No podrá enumerar los beans singleton que se registran manualmente. ex- :) no puede enumerar los beans de entorno, systemProperties, systemEnvironment. Sin embargo, estos frijoles están disponibles en el contenedor. Puede Autowire usando @Auwired Medio Ambiente env etc. stackoverflow.com/a/54863282/1840774
Velu

22

Imprima todos los nombres de los frijoles y sus clases:

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 () no muestra los beans que están registrados sin la instancia de BeanDefinition. No podrá enumerar los beans singleton que se registran manualmente. ex- :) no puede enumerar los beans de entorno, systemProperties, systemEnvironment. Sin embargo, estos frijoles están disponibles en el contenedor. Puede conectarlos automáticamente usando @Auwired Environment env, etc. stackoverflow.com/a/54863282/1840774
Velu

19

Con Spring Boot y el motor de arranque del actuador

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

puedes comprobar el punto final /beans


2
La pregunta era para Spring 2.0, no Spring Boot.
TMN

8

applicationContext.getBeanDefinitionNames () no no muestran los granos que se registran sin instancia 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);
    }       
}

}


Salida de consola

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

Como se puede ver en la salida, medio ambiente, SystemProperties, systemEnvironment granos se no se muestran utilizando context.getBeanDefinitionNames () método.

Bota de primavera

Para las aplicaciones web de arranque de primavera, todos los beans se pueden enumerar utilizando el siguiente punto final.

@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.spring. internalCachingMetadataReaderFactory "," org.springframework.boot.autoconfigure.condition.BeanTypeRegistry "," org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry "," propertySourcesPlaceholderConfigurer.springPropertiesPlaceholderConfigurer. , "preserveErrorControllerTargetClassPostProcessor "," org.springframework.context.annotation.internalAutowiredAnnotationProcessor "," org.springframework.context.annotation.internalRequiredAnnotationProcessor "," org.springframework.context.monotation.processor. ConfigurationPropertiesBindingPostProcessor "," org.springframework.scheduling.annotation.ProxyAsyncConfiguration "," org.springframework.context.annotation.internalAsyncAnnotationProcessor "," methodValidationPostProcessor "," embeddedServletContainer "messagePostProcessor", "embeddedServletContainerCustomizerBean" messageapplicationEventMulticaster "," org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration $ EmbeddedTomcat "," tomcatEmbeddedServletContainerFactory "," org.springframework.boot.autoconfigure.websocket.WebsocketSupport. org.springframework.boot.autoconfigure.web.HttpEncodingProperties "," org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration "," localeCharsetMappingsCustomizer "," org.springframework.verfigure.web. ". duplicateServerPropertiesDetector "," spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties "," org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration $ DefaultErrorViewResolverConfiguration "," conventionErrorViewResolver "," org.springframework.boot.autoconfigure.web.Automatizador " 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 "," dispatcherServletRegtext.configuration "," dispatcherServletRegtext.configuration "," dispatcherServletRegtextilConfiguración ", , "httpPutFormContentFilter", "characterEncodingFilter", "org.springframework.context.event.internalEventListenerProcessor", "org.springframework.context.event.internalEventListenerFactory", "reportGenerator", "exportController", "export.Application", "exportController", "export.Aplicación" bota.autoconfigure.AutoConfigurationPackages "," org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration "," org.springframework.boot.autoconfigure.jackson.JacksonAuto.Configuration $ Jackson2ObjectmeMapperBuilder.auto.jackson.JacksonAuto.Configuration. JacksonProperties "," standardJacksonObjectMapperBuilderCustomizer "," org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration $ JacksonObjectMapperBuilderConfiguration "," org.springframework.boot.autoconfigure.JacksonAutoConfiguration "," org.springframework.boot.autoconfigure.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", "error" basicttributes "," nombre de error "," Error de control "," nombre de error " , "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.HttpMessageConverter "," org.springframework.boot.autoconfigure.web.HttpMessageConverter "," org.springframework.boot.autoconfigure.web.HttpMessage "message," message "message,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.autoconfigurex.admin "SpringApplication "Admin" SpringApplication "Admin. , "org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration", "org.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration", "spring.info-org.springframework.boot.info.Profigura" springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration "," multipartResolver "," org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration $ RestTemplateConfiguration "," restTemplateBuilder "," org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration "," spring.devtools-org.Topring.deframework.auto.boot. 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 "]


6

Podrías intentar llamar

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

O active el registro de depuración para org.springframework. (En el arranque de primavera, eso es usar un parámetro --logging.level.org.springframework=DEBUG)


ListableBeanFactoryes una interfaz. ¿Dónde se obtendría una instancia de una clase que extienda esa interfaz para ejecutar el método getBeansOfTypeo cualquier otro método en la interfaz? Veo que lo ApplicationContextamplía, pero su ejemplo no muestra cómo adquirir uno de esos.
ErikE

Usted puede añadir un campo @Autowired ListableBeanFactory listableBeanFactoryy obtendrá uno (el tipo de implementación no debe importar)
artbristol

1

Utilizando spring-boot-starter-actuatorpuede acceder fácilmente a todos los archivos bean.

Aquí está el proceso de configuración:

  1. Agregue dependencia en gradle :

Agregue abajo en el archivo gradle:

compile("org.springframework.boot:spring-boot-starter-actuator")
  1. Habilite la seguridad en application.properties :

Agregue management.security.enabled=falseen su archivo application.property

  1. punto final de llamada / beans :

    Después de esa configuración, la primavera habilitará algunos puntos finales relacionados con las métricas. Uno de sus puntos finales es / beans Después de llamar a estos puntos finales, proporcionará un archivo json que contiene todo su bean, incluida su dependencia y alcance.

Aquí hay un archivo json de ejemplo:

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

Para obtener más información, visite los siguientes enlaces:

Espero que esto te ayudará. Gracias :)


1
primavera! = bota de primavera
Himanshu Bhardwaj

Sí, eso es verdadero hermano :). Esta solución es para arranque de velocidad.
Md. Sajedul Karim

1

Aquí hay otra forma de imprimir todos los nombres de frijoles del contexto de la aplicación de primavera:

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 ****************** 
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.