시작할 때로드되는 모든 스프링 빈을 인쇄하는 방법이 있습니까? 저는 Spring 2.0을 사용하고 있습니다.
답변:
예, ApplicationContext
전화를 걸어.getBeanDefinitionNames()
다음을 통해 컨텍스트를 얻을 수 있습니다.
ApplicationContextAware
@Inject
/로 주입 @Autowired
(2.5 이후)WebApplicationContextUtils.getRequiredWebApplicationContext(..)
관련 : Bean을 등록하여 각 Bean의 등록을 감지 할 수도 있습니다 BeanPostprocessor
. 각 빈에 대해 알려드립니다.
public class PrintBeans {
@Autowired
ApplicationContext applicationContext;
public void printBeans() {
System.out.println(Arrays.asList(applicationContext.getBeanDefinitionNames()));
}
}
모든 빈 이름과 클래스를 인쇄합니다.
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 () 는 BeanDefinition 인스턴스 없이 등록 된 Bean을 표시 하지 않습니다 .
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
출력에서 볼 수 있듯이 환경, systemProperties, systemEnvironment Bean은 context.getBeanDefinitionNames () 메소드를 사용하여 표시 되지 않습니다 .
스프링 부트 웹 애플리케이션의 경우 아래 엔드 포인트를 사용하여 모든 Bean을 나열 할 수 있습니다.
@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.springframework.boot.autoconfigure. internalCachingMetadataReaderFactory ","org.springframework.boot.autoconfigure.condition.BeanTypeRegistry ","org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry ","propertySourcesPlaceholderConfigurer ","org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.store " , "preserveErrorControllerTargetClassPostProcessor ","org.springframework.context.annotation.internalAutowiredAnnotationProcessor ","org.springframework.context.annotation.internalRequiredAnnotationProcessor ","org.springframework.context.annotation.internalCommonAnnotationProcessor ","org.springframework.boot.context.properties. ConfigurationPropertiesBindingPostProcessor ","org.springframework.scheduling.annotation.ProxyAsyncConfiguration ","org.springframework.context.annotation.internalAsyncAnnotationProcessor ","methodValidationPostProcessor ","embeddedServletContainerCustomizerBeanPostProcessor ","errorPageRegistrarBeanPostProcessor ",applicationEventMulticaster ","org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration $ EmbeddedTomcat ","tomcatEmbeddedServletContainerFactory ","org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration $ -TomcatWebSocketencoding ","websocketContainerCustomizer ","websocketContainerCustomizer " org.springframework.boot.autoconfigure.web.HttpEncodingProperties ","org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration ","localeCharsetMappingsCustomizer ","org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration ","serverProperties "," duplicateServerPropertiesDetector ","spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties ","org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration $ DefaultErrorViewResolverConfiguration ","conventionErrorViewResolver ","org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration ","errorPageCustomizer ","servletContext "," 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 ","org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration ","hiddenHttpMethodFilter " , "httpPutFormContentFilter", "characterEncodingFilter", "org.springframework.context.event.internalEventListenerProcessor", "org.springframework.context.event.internalEventListenerFactory", "reportGeneratorApplication", "exportController", "exportService", "org.springframework. 신병.autoconfigure.AutoConfigurationPackages ","org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration ","org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration $ Jackson2ObjectMapperBuilderCustomizerConfiguration ","spring.jackson-org.springframework.boot.autoconfigure.jackson. JacksonProperties ","standardJacksonObjectMapperBuilderCustomizer ","org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration $ JacksonObjectMapperBuilderConfiguration ","org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration ","jsonComponentModule ","jacksonObjectMapperBuilder ","org.springframework. boot.autoconfigure.jackson.JacksonAutoConfiguration $ JacksonObjectMapperConfiguration ","jacksonObjectMapper ","org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration ","org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration ","org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration " , "org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration", "defaultValidator", "org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration $ WhitelabelErrorViewConfiguration", "error", "beanNameViewResolver", "errorAttributes", "basicErrorController" , "org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration $ EnableWebMvcConfiguration ","org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration $ WebMvcAutoConfigurationAdapter ","mvcContentNegotiationManager ","org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration $ StringHttpMessageConverterConfiguration ","stringHttpMessageConverter ","org.springMessageConverter ","org.springMessageConverter " boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration $ MappingJackson2HttpMessageConverterConfiguration ","mappingJackson2HttpMessageConverter ","org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration ","messageConverters ","mvcConversionService ","mvcValidator ","requestMappingHandlerAdapter ","mvcResourceUrlProvider ","requestMappingHandlerMapping ","mvcPathMatcher ","mvcUrlPathHelper ","viewControllerHandlerMapping ","beanNameHandlerMapping ","resourceHandlerMapping ","defaultServletHandlerMapping ","mvcUriComponentHandlerAdapter ","handlerExceptionHandlerAdapter ","httpRequestlerExceptionHandlerAdapter " , "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.admin.SpringApplicationAdminJmxAutoConfiguration ","springApplicationAdminRegistrar " , "org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration", "org.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration", "spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties", "org. 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.autoconfigure.DevToolsProperties "," 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 "]
당신은 전화를 시도 할 수 있습니다
org.springframework.beans.factory.ListableBeanFactory.getBeansOfType(Object.class)
또는에 대한 디버그 로깅을 설정 org.springframework
합니다. (스프링 부트에서는 매개 변수를 사용합니다. --logging.level.org.springframework=DEBUG
)
ListableBeanFactory
인터페이스입니다. 인터페이스에서 메서드 getBeansOfType
또는 다른 메서드 를 실행하기 위해 해당 인터페이스를 확장하는 클래스의 인스턴스를 어디에서 얻을 수 있습니까 ? 나는 ApplicationContext
그것이 그것을 확장한다고 생각하지만, 당신의 예는 그것들 중 하나를 얻는 방법을 보여주지 않습니다.
@Autowired ListableBeanFactory listableBeanFactory
당신은 하나 (구현 유형해야 문제가되지) 얻을 것이다
사용 spring-boot-starter-actuator
하면 모든 빈에 쉽게 접근 할 수 있습니다.
설정 프로세스는 다음과 같습니다.
gradle 파일에 다음을 추가하십시오.
compile("org.springframework.boot:spring-boot-starter-actuator")
management.security.enabled=false
application.property 파일에 추가 하십시오.
/ beans 끝점 호출 :
그 설정 후 스프링은 일부 메트릭 관련 엔드 포인트를 활성화합니다. 엔드 포인트 중 하나는 / beans입니다. 이 엔드 포인트를 호출 한 후 종속성 및 범위를 포함하여 모든 Bean을 포함하는 json 파일을 제공합니다.
다음은 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":[]}]
자세한 정보는 다음 링크를 참조하십시오.
이것이 당신을 도울 것입니다. 감사 :)
다음은 스프링 애플리케이션 컨텍스트에서 모든 빈 이름을 인쇄하는 또 다른 방법입니다.
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
인터페이스 를 구현하는 이유 는 Spring 프레임 워크 가 애플리케이션 컨텍스트에 액세스 할 수있는 기회 를 제공하기 때문 입니다.@Configuration
의도 한 응용 프로그램 컨텍스트 의 클래스에 배치해야합니다 .