[java] 로드 된 모든 Spring Bean을 인쇄하십시오.

시작할 때로드되는 모든 스프링 빈을 인쇄하는 방법이 있습니까? 저는 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";
    }
}


답변

스프링 부트와 액추에이터 스타터

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

끝점을 확인할 수 있습니다 /beans


답변

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)


답변

사용 spring-boot-starter-actuator하면 모든 빈에 쉽게 접근 할 수 있습니다.

설정 프로세스는 다음과 같습니다.

  1. gradle에 종속성을 추가하십시오 .

gradle 파일에 다음을 추가하십시오.

compile("org.springframework.boot:spring-boot-starter-actuator")
  1. application.properties에 대한 보안 활성화 :

management.security.enabled=falseapplication.property 파일에 추가 하십시오.

  1. / 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":[]}]

자세한 정보는 다음 링크를 참조하십시오.

이것이 당신을 도울 것입니다. 감사 🙂