¿Hay alguna manera de imprimir todos los frijoles de primavera que se cargan al inicio? Estoy usando Spring 2.0.
¿Hay alguna manera de imprimir todos los frijoles de primavera que se cargan al inicio? Estoy usando Spring 2.0.
Respuestas:
Sí, contacta ApplicationContext
y llama.getBeanDefinitionNames()
Puede obtener el contexto mediante:
ApplicationContextAware
@Inject
/ @Autowired
(después de 2.5)WebApplicationContextUtils.getRequiredWebApplicationContext(..)
Relacionado: también puede detectar el registro de cada bean registrando un BeanPostprocessor
bean. Se notificará para cada bean.
public class PrintBeans {
@Autowired
ApplicationContext applicationContext;
public void printBeans() {
System.out.println(Arrays.asList(applicationContext.getBeanDefinitionNames()));
}
}
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";
}
}
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);
}
}
}
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.
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 "]
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
)
ListableBeanFactory
es una interfaz. ¿Dónde se obtendría una instancia de una clase que extienda esa interfaz para ejecutar el método getBeansOfType
o cualquier otro método en la interfaz? Veo que lo ApplicationContext
amplía, pero su ejemplo no muestra cómo adquirir uno de esos.
@Autowired ListableBeanFactory listableBeanFactory
y obtendrá uno (el tipo de implementación no debe importar)
Utilizando spring-boot-starter-actuator
puede acceder fácilmente a todos los archivos bean.
Aquí está el proceso de configuración:
Agregue abajo en el archivo gradle:
compile("org.springframework.boot:spring-boot-starter-actuator")
Agregue management.security.enabled=false
en su archivo application.property
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 :)
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 ******************
ApplicationContextAware
interfaz es porque Spring Framework le da la oportunidad de acceder al contexto de la aplicación. Debe colocarlo en la@Configuration
clase para el contexto de aplicación previsto.