로드된 스프링 콩을 모두 인쇄합니다(스프링 부트).
스프링 부트 앱의 일부로 로드된 모든 콩의 이름을 알 수 있는 방법은 무엇입니까?서버 부팅 후 로딩되는 콩의 상세 내용을 출력하기 위한 코드를 메인 방식으로 설정해 주셨으면 합니다.
spring-boot의 시작 가이드에서 알 수 있듯이http://https://spring.io/guides/gs/spring-boot/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
};
}
}
댓글에서 @Velu가 언급했듯이 수동으로 등록된 콩은 나열되지 않습니다.
필요한 경우 getSingletonNames()를 사용할 수 있습니다.그러나 조심하라.이 메서드는 이미 인스턴스화된 콩만 반환합니다.콩이 아직 인스턴스화되지 않은 경우 다음 날짜까지 반환되지 않습니다.getSingletonNames().
액추에이터 사용을 제안해도 될까요?다음과 같은 몇 가지 엔드포인트를 제공합니다./beans응용 프로그램의 모든 콩이 나열됩니다.「서버가 기동하면」이라고 하는 것은, Web 애플리케이션의 선택사항입니다.
액추에이터 설정 방법
액추에이터의 엔드포인트 목록
http://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html
음, 이 질문은 이미 답변이 되었지만, 저는 Java 8의 변형에 대한 답변을 드리고 싶습니다.
Arrays.asList(context.getBeanDefinitionNames()).stream().sorted().forEach(System.out::println);
Java 8을 실행합시다!!!
실제로 이 클래스는 @SpringBoot Application 수정 외에 만드는 것이 좋습니다.
@Component
public class ContextTeller implements CommandLineRunner {
@Autowired
ApplicationContext applicationContext;
@Override
public void run(String... args) throws Exception {
System.out.println("-------------> just checking!");
System.out.println(Arrays.asList(applicationContext.getBeanDefinitionNames()));
}}
이렇게 하면 Spring Boot은 이 클래스를 로드하고 컨텍스트 로드 직후에 실행됩니다.그러면 파일을 삭제하기만 하면 모든 것이 깨끗해집니다.
applicationContext.getBeanDefinitionNames()는 BeanDefinition 인스턴스 없이 등록된 콩을 표시하지 않습니다.
스프링 부트 Web 애플리케이션의 경우는, 다음의 엔드 포인트를 사용해 모든 콩을 일람표시할 수 있습니다.
@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;
}
}
[ auto Configuration Report ] 、 [ spring applicationArguments ] 、 [ spring BootBanner ] 、 [ spring Boot Logging System ] 、 [ ] 、 [ mentproperproperproperproper"mentmentment ] 、 [ system Properties ] 、 [ system Environvironment ] 、 [ ] 、 [ or . or . springframework . context . ]internal Configuration Annotation Processor", "org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory", "org.springframework.boot.autoconfigure.condition"입니다.BeanTypeRegistry", "또는.springframework.context.annotation"을 참조하십시오.ConfigurationClassPostProcessor.importRegistry", "propertySourcesPlaceholderConfigr", "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", "orsprameworkconfigure"입니다.Embedded Servlet Container자동설정$임베디드Tomcat", "tomcatEmbeddedServletContainerFactory", "org.springframework.boot.autoconfigure"를 선택합니다.웹 소켓.WebSocketAutoConfiguration$Tomcat WebSocket Configuration", "websocket Container Customizer", "spring.http.encoding-org.springframework.boot.autoconfigure.web"입니다.HttpEncodingProperties", "org.springframework.boot.autoconfigure.web.Http Encoding(Http Encoding)AutoConfiguration", "localeCharsetMappingsCustomizer", "org.springframework.boot.autoconfigure.web.서버 속성자동 구성", "serverProperties", "duplicateServerProperties"디텍터", "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.멀티파트자동 구성", "multipartConfigElement", "org.springframework.boot.autoconfigure"를 선택합니다.web.Dispatcher ServletAutoConfiguration$DispatcherServletRegistrationConfiguration", "org.springframework.boot.autoconfigure.web.Dispatcher ServletAutoConfiguration$DispatcherServletConfiguration", "dispatcherServlet", "dispatcherServletRegistration", "requestContextFilter", "org.springframework.boot.autoconfigure.web"입니다.WebMvcAutoConfiguration", "HttpMethodFilter", "httpPutFormContentFilter", "characterEncodingFilter", "org.springframework.context.event.internalEventListenerProcessor", "org.spramework.context.context.inalEventListenerator", "ReportGenerator, "ReportFactory"AutoConfigurationPackages", "org.springframework.boot.autoconfigure.context.속성 플레이스 홀더자동 구성", "org.springframework.boot.autoconfigure.jackson"을 지정합니다.JacksonAutoConfiguration$Jackson2ObjectMapperBuilderCustomizerConfiguration", "spring.jackson-org.springframework.boot.autoconfigure.jackson.Jackson Properties", "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"입니다.웹 소켓.WebSocketAutoConfiguration", "org.springframework.boot.autoconfigure.web.Embedded Servlet Container자동 구성", "org.springframework.boot.autoconfigure"를 선택합니다.web.Dispatcher ServletAutoConfiguration", "org.springframework.boot.autoconfigure.validation.확인AutoConfiguration", "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.Http Message ConvertersAutoConfiguration$StringHttpMessageConverterConfiguration", stringHttpMessageConverter, org.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration$MappingJackson2Http Message Converter Configuration", "mapping Jackson2"HttpMessageConverter", "org.springframework.boot.autoconfigure.web" 입니다.Http Message Converters자동설정", "messageConverters", "mvcConversionService", "mvcValidator", "requestMappingHandlerAdapter", "mvcResourceUrlProvider", "requestMappingHandlerMapping", "mvcPathMatc"Matcer, "개요"tor", "httpRequestHandlerAdapter", "simpleControllerHandlerAdapter", "handlerExceptionResolver", "mvcViewResolver", "org.springframework.boot.autoconfigureweb"이 있습니다.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter$FaviconConfiguration", "faviconRequestHandlerMapping", "viewResolver", "viewResolver", "welcomePageHandlerMapping", "bootframeConfigure"입니다.JmxAutoConfiguration", "objectNamingStrategy", "mbeanServer", "mbeanExporter", "org.springframework.boot.autoconfigure.admin"입니다.Spring ApplicationAdminJmxAutoConfiguration", "springApplicationAdminRegistrar", "org.springframework.boot.autoconfigure.context.구성 속성자동 구성", "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.자동 설정DevToolsProperties", "org.springframework.boot.devtools"를 참조하십시오.자동 설정Local Dev Tools(LocalDevToolsAutoConfiguration$RestartConfiguration", "fileSystemWatcherFactory", "classPathRestartStrategy", "classPathFileSystemWatcher", "hateoAsObjenesisCacheDisabler", "또는 springframework.boot.devtools.자동 설정Local Dev Tools(LocalDevToolsAutoConfiguration$LiveReloadConfiguration$LiveReloadServerConfiguration", "org.springframework.boot.devtools.자동 설정Local Dev Tools(LocalDevToolsAutoConfiguration$LiveReloadConfiguration", "옵션 LiveReloadServer", "org.springframework.boot.devtools"를 선택합니다.자동 설정Local Dev Tools(LocalDevTools자동 설정", "라이프 사이클 프로세서" ]
출력에서 알 수 있듯이 context.getBeanDefinitionNames() 메서드를 사용하면 환경, systemProperties, systemEnvironment bean은 표시되지 않습니다.
@Component
public class ContextTeller implements CommandLineRunner {
@Autowired
public ApplicationContext applicationContext;
@Override
public void run(String... args) throws Exception {
System.out.println("<------------- Beans loaded --------------->");
Arrays.asList(applicationContext.getBeanDefinitionNames()).stream().forEach(System.out::println);
}
}
@Zergleb에서 언급했듯이 액추에이터를 사용하는 것도 적절하지만 참조 문서에 따르면 기본적으로 이 엔드포인트는 "웹"을 통해 더 이상 노출되지 않습니다.따라서 엔드포인트에 액세스하려면 다음 단계를 고려해야 합니다.
를 '보다 낫다'에 더하세요.
pom.xml<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>다음 두 가지 속성을 application.properties 파일에 추가합니다.
management.endpoints.web.exposure.include=beans
management.endpoint.beans.enabled=true
- 를 사용하여 .
/actuator/beans" " "
이 요건에 대한 작은 실험을 한 번 실시하여 이 솔루션을 찾았습니다.WEB, 액추에이터, HAL, Devtools 등의 모듈을 선택하면서 SpringBoot을 만들었습니다.응용 프로그램 속성에서 액추에이터에 있는 모든 엔드포인트를 로드하도록 아래 속성을 구성했습니다.
management.displaces를 클릭합니다.web.deb.deb=*
액추에이터 정보는 http://localhost:8080/actuator에서 확인할 수 있습니다.그러면 모든 응용 프로그램 정보가 액추에이터, 상태, 정보 등과 함께 표시됩니다.springboot 어플리케이션에 의해 내부적으로 작성된 모든 콩을 로드하는http://localhost:8080/actuator/beans 를 찾을 수 있습니다.
원두 정보를 모두 볼 수 있게 되면 메인 클래스에서 다시 인쇄할 필요는 없다고 생각합니다.
어플리케이션에 rest-hal-browser 의존관계가 이미 설정되어 있기 때문에 URL http://localhost:8080을 로드하면 UI가 로드되어 다른 엔드포인트가 검색됩니다.아래 이미지에서 액추에이터 정보를 검색하고 있습니다.
모든 콩을 쉽게 구할 수 있는 방법
ApplicationContext ctx =SpringApplication.run(DemoApplication.class, args);
String [] beans = ctx.getBeanDefinitionNames();
Arrays.sort(beans);
System.out.println("#############");
for(String s:beans) {
System.out.println(s + " of type " + ctx.getBean(s).getClass());
}
언급URL : https://stackoverflow.com/questions/33348937/print-all-the-spring-beans-that-are-loaded-spring-boot
'codememo' 카테고리의 다른 글
| JSON에 대한 쿼리 언어가 있습니까? (0) | 2023.02.22 |
|---|---|
| 이게 다음인가요?JS 폴더 구조를 권장합니다. (0) | 2023.02.22 |
| 각도 $scope.안전한 $190 대 $190 (0) | 2023.02.22 |
| 데이터에 연속되는 물음표가 포함되어 있는 경우 이해할 수 없는 jQuery $.ajax() 동작 (0) | 2023.02.22 |
| WordPress: get_the_content()와 the_content()의 차이 (0) | 2023.02.22 |
