您现在的位置是:亿华云 > IT科技
你的Springboot应用到底启动了哪些bean?这两种方式可以帮你获取
亿华云2025-10-03 11:44:38【IT科技】8人已围观
简介1. 概述在本文中,我们将探索在容器中获取所有spring管理的bean的相关技术。这有神马用?主要是用于排查问题。一般都是我们创建的某一个bean没有启动的问题。毕竟工作中总是会遇到各种各样的bug
1. 概述
在本文中,底启动我们将探索在容器中获取所有spring管理的应用bean的相关技术。这有神马用?种方主要是用于排查问题。一般都是帮获我们创建的某一个bean没有启动的问题。毕竟工作中总是底启动会遇到各种各样的bug。提前了解一些没有坏处。应用
2. IoC容器
bean是种方spring管理的应用程序的基础,所有bean都驻留在IOC容器中,帮获该容器负责管理它们的底启动生命周期。
我们可以通过两种方式获取该容器内所有bean的高防服务器应用列表:
使用ListableBeanFactory接口 使用Spring Boot Actuator3.使用ListableBeanFactory接口
ListableBeanFactory接口提供了getBeanDefinitionNames()方法,该方法返回在这个工厂中定义的种方所有bean的名称。您可以在官方文档中找到所有已知子接口及其实现类的帮获列表。我们来看这种方式如何获取所有的底启动bean。
第一步:创建一个Controller
@Controller public class FooController { @Autowired private FooService fooService; @RequestMapping(value="/displayallbeans") public String getHeaderAndBody(Map model){ model.put("header",应用 fooService.getHeader()); model.put("message", fooService.getBody()); return "displayallbeans"; } }这个Controller依赖于另一个FooService。
第二步:创建Service
@Service public class FooService { public String getHeader() { return "Display All Beans"; } public String getBody() { return "展示所有beans的种方案例"; } }注意,我们在这里创建了两个不同的bean:
fooControllerfooService这里使用applicationContext对象并调用它的getBeanDefinitionNames()方法,该方法将返回applicationContext容器中的所有bean:
第三步:设置SpringBootApplication启动类
@SpringBootApplication public class DemoApplication { private static ApplicationContext applicationContext; public static void main(String[] args) { applicationContext = SpringApplication.run(DemoApplication.class, args); displayAllBeans(); } public static void displayAllBeans() { String[] allBeanNames = applicationContext.getBeanDefinitionNames(); for(String beanName : allBeanNames) { System.out.println(beanName); } } }第四步:测试打印
这将打印applicationContext容器中的所有bean:
注意,除了我们定义的bean之外,它还将记录该容器中的所有其他bean。源码库为了清楚起见,我们在这里省略了它们,因为它们有很多。
4. 使用Spring Boot Actuator
Spring Boot Actuator提供了用于监控应用程序统计信息的端点。下面看看这种方式:
第一步:添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>第二步:修改application.properties
management.endpoints.web.exposure.include=*把上面代码添加到properties文件中。
第三步:使用发布端点查看
由于这里的Actuator没有配置,所以显示的比较乱。关于Actuator的配置,会在下一篇文章中呈现。
5. 结论
在本文中,我们了解了如何使用ListableBeanFactory接口和Spring Boot Actuator在Spring IoC容器中显示所有bean。希望对你有点帮助。
本文转载自微信公众号「愚公要移山」,可以通过以下二维码关注。转载本文请联系愚公要移山公众号。
很赞哦!(25946)