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


分享到:


相關文章: