Czy istnieje sposób na wydrukowanie wszystkich ziaren wiosennych, które są ładowane podczas uruchamiania? Używam Spring 2.0.
Czy istnieje sposób na wydrukowanie wszystkich ziaren wiosennych, które są ładowane podczas uruchamiania? Używam Spring 2.0.
Odpowiedzi:
Tak, odbierz ApplicationContext
i zadzwoń.getBeanDefinitionNames()
Możesz uzyskać kontekst poprzez:
ApplicationContextAware
@Inject
/ @Autowired
(po 2,5)WebApplicationContextUtils.getRequiredWebApplicationContext(..)
Powiązane: rejestrację każdego ziarna można również wykryć, rejestrując BeanPostprocessor
ziarno. Zostanie powiadomiony o każdym ziarnie.
public class PrintBeans {
@Autowired
ApplicationContext applicationContext;
public void printBeans() {
System.out.println(Arrays.asList(applicationContext.getBeanDefinitionNames()));
}
}
Wydrukuj wszystkie nazwy ziaren i ich klasy:
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 () czy nie pokazać ziarna, które są zarejestrowane bez instancji 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
Jak widać w danych wyjściowych, komponenty bean environment, systemProperties, systemEnvironment nie zostaną wyświetlone przy użyciu funkcji context.getBeanDefinitionNames () metody .
W przypadku aplikacji internetowych uruchamianych wiosną wszystkie komponenty bean można wyświetlić za pomocą poniższego punktu końcowego.
@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.springfraut. internalCachingMetadataReaderFactory "," org.springframework.boot.autoconfigure.condition.BeanTypeRegistry "," org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry "," propertySourcesPlaceholderConfigurer "," org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry "," propertySourcesPlaceholderConfigurer "," org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry "," propertySourcesPlaceholderConfigurer "," org.springframework. , "preserveErrorControllerTargetClassPostProcessor "," org.springframework.context.annotation.internalAutowiredAnnotationProcessor "," org.springframework.context.annotation.internalRequiredAnnotationProcessor "," org.springframework.context.annotationProcessor. " ConfigurationPropertiesBindingPostProcessor "," org.springframework.scheduling.annotation.ProxyAsyncConfiguration "," org.springframework.context.annotation.internalAsyncAnnotationProcessor "," methodValidationPostProcessor "," embeddedServletContainerCustomessorProcessorBeanProcessorBean "," message "," embeddedServletContainerCustomessorProcessorBeanProcessorBean ","applicationEventMulticaster "," org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration $ EmbeddedTomcat "," tomcatEmbeddedServletContainerFactory "," org.springframework.boot.autoconfigure.websocket.WebSttdedTomcat "," tomcatEmbeddedServletContainerFactory "," org.springframework.boot.autoconfigure.websocket. 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.web. duplicateServerPropertiesDetector "," spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties "," org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration $ DefaultErrorViewResolverConfiguration "," conventionErrorViewResolver "," org.springframework.boot.autoconfigure.web.ErrorViewResolverConfiguration "," conventionErrorViewResolver "," org.springframework.boot.autoconfigure.web. 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.ServletAutoConfiguration. , "httpPutFormContentFilter", "characterEncodingFilter", "org.springframework.context.event.internalEventListenerProcessor", "org.springframework.context.event.internalEventListenerFactory", "reportGeneratorApplication", "exportController. bagażnik.autoconfigure.AutoConfigurationPackages "," org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration "," org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration $ Jackson2ObjectMapperBuilderCustomoture.Configuration "," org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration $ Jackson2ObjectMapperBuilderCustomoture.Configuration.jameworkson ", JacksonProperties "," standardJacksonObjectMapperBuilderCustomizer "," org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration $ JacksonObjectMapperBuilderConfiguration "," org.springframework.boot.autoconfigure.jackson.Jackson.JacksonAutoConfiguration $ JacksonObjectMapperBuilderConfiguration "," org.springframework.boot.autoconfigure.jackson.Jackson.ModoBuilder, "org.springframework.boot.autoconfigure.jackson.Jackson.AutoConfiguration," boot.autoconfigure.jackson.JacksonAutoConfiguration $ JacksonObjectMapperConfiguration "," jacksonObjectMapper "," org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration "," org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration.websocket.WebSocketAutoConfiguration "," org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration.websocket.WebSocketAutoConfiguration "," , "org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration", "defaultValidator", "org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration $ WhitelabelErrorViewConfiguration", "error", "beanNtribameViewResolver.boot.autoconfigure.web.ErrorMvcAutoConfiguration $ WhitelabelErrorViewConfiguration", "błąd", "beanNtribameViewResolverArror", , „org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration $ EnableWebMvcConfiguration "," org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration $ WebMvcAutoConfigurationAdapter "," mvcContentNegotiationManager "," org.springframework.boot.autoconfigpertageConfiguration.web.boot.autoconfigageConfiguration.web. boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration $ MappingJackson2HttpMessageConverterConfiguration "," mappingJackson2HttpMessageConverter "," org.springframework.boot.autoconfigure.web.HttpMessageConverterConfiguration "," mappingJackson2HttpMessageConverter "," org.springframework.boot.autoconfigure.web.HttpMessageConverterConfiguration "," mappingJackson2HttpMessageConverter "," org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConversion "," mrequestMappingHandlerAdapter”, "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.autoconfigure.adminication "," org.springframework.boot.autoconfigure.adminication " , „org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration”, „org.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration”, „spring.info-org.springframework.boot.autoconfigure.info.Project”, „org.springframework.boot.autoconfigure.info.Project” 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.evroperties "," org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration $ RestartConfiguration "," fileSystemWatcherFactory "," classPathRestartStrategy "," classPathFileSystemWatcher "," hateoasLocalDevToolsAutoConfiguration $ RestartConfiguration "," fileSystemWatcherFactory "," classPathRestartStrategy "," classPathFileSystemWatcher "," hateoas LiveolsObjenesisCacheDisabler configuration "ConfigurationConfig. org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration $ LiveReloadConfiguration "," optionalLiveReloadServer "," org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration "," lifecycleProcessor "]
Możesz spróbować zadzwonić
org.springframework.beans.factory.ListableBeanFactory.getBeansOfType(Object.class)
Lub włącz rejestrowanie debugowania dla org.springframework
. (W butach wiosennych używa się parametru --logging.level.org.springframework=DEBUG
)
ListableBeanFactory
to interfejs. Skąd można uzyskać instancję klasy rozszerzającej ten interfejs w celu wykonania metody getBeansOfType
lub dowolnej innej metody w interfejsie? Widzę, że ApplicationContext
to przedłuża, ale twój przykład nie pokazuje, jak zdobyć jedną z nich.
@Autowired ListableBeanFactory listableBeanFactory
i je otrzymasz (typ implementacji nie powinien mieć znaczenia)
Za pomocą spring-boot-starter-actuator
można łatwo uzyskać dostęp do wszystkich fasoli.
Oto proces konfiguracji:
Dodaj poniżej do pliku gradle:
compile("org.springframework.boot:spring-boot-starter-actuator")
Dodaj management.security.enabled=false
do pliku application.property
punkt końcowy połączenia / fasoli :
Po tej konfiguracji wiosna włączy niektóre punkty końcowe związane z metrykami. Jednym z jego punktów końcowych jest / fasola Po wywołaniu tych punktów końcowych dostarczy plik json, który zawiera wszystkie komponenty bean, w tym jego zależności i zakres.
Oto przykładowy plik 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":[]}]
Aby uzyskać więcej informacji, odwiedź poniższe linki:
Mam nadzieję, że to ci pomoże. Dzięki :)
Oto inny sposób wydrukowania wszystkich nazw ziaren z kontekstu aplikacji wiosennej:
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
interfejsu jest to, że Spring Framework daje mu szansę na dostęp do kontekstu aplikacji. Powinieneś umieścić go w@Configuration
klasie dla zamierzonego kontekstu aplikacji.