12.26 查看Spring Boot在啟動的時候注入了哪些bean?

Spring Boot啟動的時候需要自動加載許多Bean實現最小化配置,下面我們通過代碼輸出Spring啟動後加載的所有Bean信息。



在Spring boot應用入口,添加如下代碼:

<code>@SpringBootApplication
public class SpringbootFirstApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootFirstApplication.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);
}
};
}
}/<code>

CommandLineRunner方法標記為@Bean,在啟動spring boot應用的時候會運行。它檢索應用程序創建的所有bean,或者由spring boot自動添加的bean。接著排序,並打印輸出。

查看Spring Boot在啟動的時候注入了哪些bean?

查看輸出結果,spring boot 會自動注入beans如下:

<code>Let's inspect the beans provided by Spring Boot:
application
beanNameHandlerMapping
defaultServletHandlerMapping
dispatcherServlet
embeddedServletContainerCustomizerBeanPostProcessor
handlerExceptionResolver
helloController
httpRequestHandlerAdapter
messageSource
mvcContentNegotiationManager
mvcConversionService
mvcValidator
org.springframework.boot.autoconfigure.MessageSourceAutoConfiguration
org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$DispatcherServletConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration
org.springframework.boot.context.embedded.properties.ServerProperties
org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor
org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration
propertySourcesBinder
propertySourcesPlaceholderConfigurer
requestMappingHandlerAdapter
requestMappingHandlerMapping
resourceHandlerMapping
simpleControllerHandlerAdapter
tomcatEmbeddedServletContainerFactory
viewControllerHandlerMapping/<code>

另外一個方法是通過在spring boot應用的pom.xml中添加Actuator依賴包:

<dependency>

<groupid>org.springframework.boot/<groupid>

<artifactid>spring-boot-starter-actuator/<artifactid>

同時在application.properties 配置文件中開啟Actuator端口:

management.endpoints.web.exposure.include=*


然後啟動spring boot應用,訪問/beans 端點也可以獲取到bean列表。

http://localhost:8080/actuator/beans


分享到:


相關文章: