C'è un modo per stampare tutti i bean di primavera caricati all'avvio? Sto usando Spring 2.0.
C'è un modo per stampare tutti i bean di primavera caricati all'avvio? Sto usando Spring 2.0.
Risposte:
Sì, ApplicationContext
contattaci e chiama.getBeanDefinitionNames()
Puoi ottenere il contesto:
ApplicationContextAware
@Inject
/ @Autowired
(dopo 2.5)WebApplicationContextUtils.getRequiredWebApplicationContext(..)
Correlati: è anche possibile rilevare la registrazione di ciascun bean registrando un BeanPostprocessor
bean. Verrà notificato per ogni bean.
public class PrintBeans {
@Autowired
ApplicationContext applicationContext;
public void printBeans() {
System.out.println(Arrays.asList(applicationContext.getBeanDefinitionNames()));
}
}
Stampa tutti i nomi dei bean e le sue classi:
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 () non senza mostrare i fagioli che sono registrati senza esempio 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
Come puoi vedere nell'output, environment, systemProperties, i bean systemEnvironment non verranno visualizzati utilizzando il metodo context.getBeanDefinitionNames () .
Per le applicazioni Web di avvio primaverile, tutti i bean possono essere elencati utilizzando l'endpoint seguente.
@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.sigure.spring. internalCachingMetadataReaderFactory "," org.springframework.boot.autoconfigure.condition.BeanTypeRegistry "," org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry "," propertySourcesPlaceholderConfigurer "," org.sourcesPlaceholderConfigurer. , "PreservaErrorControllerTargetClassPostProcessor "," org.springframework.context.annotation.internalAutowiredAnnotationProcessor "," org.springframework.context.annotation.internalRequiredAnnotationProcessor "," org.springframeframework.context.pertorio. ConfigurationPropertiesBindingPostProcessor "," org.springframework.scheduling.annotation.ProxyAsyncConfiguration "," org.springframework.context.annotation.internalAsyncAnnotationProcessor "," methodValidationPostProcessor "," embeddedServletPostProcessor "," embeddedServletPostProcessoreProcessore "," embeddedServletPostProcessorapplicationEventMulticaster "," org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration $ EmbeddedTomcat "," tomcatEmbeddedServletContainerFactory "," org.springframework.boot.autoconfigure.websocket.WebigurizerSocket "," tomcatEmbeddedServletContainerFactory "," org.springframework.boot.autoconfigure.websocket.WebigurizerSocket " org.springframework.boot.autoconfigure.web.HttpEncodingProperties "," org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration "," localeCharsetMappingsCustomizer "," org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration "," localeCharsetMappingsCustomizer "," org.springframework.boot.autoconfigure.perfiguration "," 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.autoconfigure.webroreconfiguration "," conventionErrorViewResolver "," org.springframework.boot.autoconfigure.webror "error 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 $ DispatcherServletConfiguration "," org.springframework.boot.autoconfigure.web. , "httpPutFormContentFilter", "characterEncodingFilter", "org.springframework.context.event.internalEventListenerProcessor", "org.springframework.context.event.internalEventListenerFactory", "reportGeneratorApplication", "exportCervice. stivale.autoconfigure.AutoConfigurationPackages "," org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration "," org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration $ Jackson2ObjectMapperBuigurotecustomizer.configuration ", springoconfiguration. JacksonProperties "," standardJacksonObjectMapperBuilderCustomizer "," org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration $ JacksonObjectMapperBuilderConfiguration "," org.springframework.boot.autoconfigure.jackson.Jackon.JacksonAutoConfiguration $ JacksonObjectMapperBuilderConfiguration "," org.springframework.boot.autoconfigure.jackson.Jackonprule ". boot.autoconfigure.jackson.JacksonAutoConfiguration $ JacksonObjectMapperConfiguration "," jacksonObjectMapper "," org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration "," org.springframework.boot.autoconfigure.web.EmbeddedServletConframe.EmbeddedServletContainerFiguration " , "org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration", "defaultValidator", "org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration $ WhitelabelErrorViewConfiguration", "error", "beanrrribErrorController", "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.HttpMessageConverterConfiguration "," mappingJackson2HttpMessageConverter "," org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration "," messageConvertersAutoConfrequestMappingHandlerAdapter", "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.autoconfigureJistrategy "," mbeanServer "," mbeanExporter "," org.springframework.boot. , "org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration", "org.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration", "spring.info-org.springframework.boot.autoconjectInfo.Properties". springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration "," multipartResolver "," org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration $ RestTemplateConfiguration "," restTemplateBuilder "," org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration "," spring.devtools-org.sprotevools.doc. 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 "]
Potresti provare a chiamare
org.springframework.beans.factory.ListableBeanFactory.getBeansOfType(Object.class)
Oppure attiva la registrazione di debug per org.springframework
. (Nell'avvio di primavera, utilizza un parametro --logging.level.org.springframework=DEBUG
)
ListableBeanFactory
è un'interfaccia. Dove si otterrebbe un'istanza di una classe che estende quell'interfaccia per eseguire il metodo getBeansOfType
o qualsiasi altro metodo nell'interfaccia? Vedo che lo ApplicationContext
estende, ma il tuo esempio non mostra come acquisirne uno.
@Autowired ListableBeanFactory listableBeanFactory
e ne otterrai uno (il tipo di implementazione non dovrebbe avere importanza)
Usando spring-boot-starter-actuator
puoi accedere facilmente a tutti i bean.
Ecco il processo di installazione:
Aggiungi muggito nel file gradle:
compile("org.springframework.boot:spring-boot-starter-actuator")
Aggiungi management.security.enabled=false
al tuo file application.property
endpoint chiamata / bean :
Dopo quella configurazione, la primavera abiliterà alcuni endpoint relativi alle metriche. Uno dei suoi endpoint è / bean. Dopo aver chiamato questo endpoint, fornirà un file json che contiene tutto il tuo bean, inclusa la dipendenza e l'ambito.
Ecco un file json di esempio:
[{"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":[]}]
Per maggiori informazioni visita i link seguenti:
Spero che questo ti possa aiutare. Grazie :)
Ecco un altro modo per stampare tutti i nomi dei bean dal contesto dell'applicazione 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 ******************
ApplicationContextAware
interfaccia è perché il framework Spring gli dà la possibilità di accedere al contesto dell'applicazione. Dovresti inserirlo nella@Configuration
classe per il contesto dell'applicazione previsto.