baeldung 2024-01-08
1. 概述
在本文中,我们将探讨几种不同的技术,用于列出 Spring 容器中所有由 Spring 管理的 Bean。
2. IoC 容器
Bean 是 Spring 管理应用程序的基础;所有 Bean 都驻留在 IoC(控制反转)容器中,该容器负责管理它们的生命周期。
我们可以通过以下两种方式获取容器中所有 Bean 的列表:
- 使用
ListableBeanFactory接口 - 使用 Spring Boot Actuator
3. 使用 ListableBeanFactory 接口
ListableBeanFactory 接口提供了 getBeanDefinitionNames() 方法,该方法返回此工厂中定义的所有 Bean 的名称。所有预先加载其 Bean 定义的 Bean 工厂都会实现此接口,以便枚举所有的 Bean 实例。
你可以在官方文档中找到该接口的所有已知子接口及其具体实现类的列表。
示例说明:本例使用的是一个 Spring Boot 应用程序。
首先,我们创建一些 Spring Bean。让我们创建一个简单的 Spring 控制器 FooController:
@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";
}
}
该控制器依赖于另一个 Spring Bean FooService:
@Service
public class FooService {
public String getHeader() {
return "Display All Beans";
}
public String getBody() {
return "This is a sample application that displays all beans "
+ "in Spring IoC container using ListableBeanFactory interface "
+ "and Spring Boot Actuators.";
}
}
注意,这里我们创建了两个不同的 Bean:
fooControllerfooService
在运行此应用程序时,我们将使用 applicationContext 对象,并调用其 getBeanDefinitionNames() 方法,该方法将返回 applicationContext 容器中的所有 Bean:
@SpringBootApplication
public class Application {
private static ApplicationContext applicationContext;
public static void main(String[] args) {
applicationContext = SpringApplication.run(Application.class, args);
displayAllBeans();
}
public static void displayAllBeans() {
String[] allBeanNames = applicationContext.getBeanDefinitionNames();
for(String beanName : allBeanNames) {
System.out.println(beanName);
}
}
}
这将打印出 applicationContext 容器中的所有 Bean:
fooController
fooService
// 其他 Bean
注意:除了我们自己定义的 Bean 外,它还会记录容器中的所有其他 Bean。为清晰起见,此处省略了这些内容,因为数量相当多。
4. 使用 Spring Boot Actuator
Spring Boot Actuator 提供了一系列端点(endpoints),用于监控应用程序的运行状态。
其中包含许多内置端点,例如 /beans。该端点会显示应用程序中所有由 Spring 管理的 Bean 的完整列表。你可以在官方文档中查看所有可用端点的完整列表。
现在,只需访问 URL:http://<地址>:<管理端口>/beans。如果你没有单独指定管理端口,则可以使用默认的服务器端口。该请求将返回一个 JSON 响应,展示 Spring IoC 容器中的所有 Bean:
[
{
"context": "application:8080",
"parent": null,
"beans": [
{
"bean": "fooController",
"aliases": [],
"scope": "singleton",
"type": "com.baeldung.displayallbeans.controller.FooController",
"resource": "file [E:/Workspace/tutorials-master/spring-boot/target/classes/com/baeldung/displayallbeans/controller/FooController.class]",
"dependencies": [
"fooService"
]
},
{
"bean": "fooService",
"aliases": [],
"scope": "singleton",
"type": "com.baeldung.displayallbeans.service.FooService",
"resource": "file [E:/Workspace/tutorials-master/spring-boot/target/classes/com/baeldung/displayallbeans/service/FooService.class]",
"dependencies": []
}
// ... 其他 Bean
]
}
]
当然,该响应同样包含容器中的许多其他 Bean,但为了清晰起见,此处已省略。
如果你想深入了解 Spring Boot Actuator,可以参考 Spring Boot Actuator 官方指南。
5. 结论
在本文中,我们学习了如何通过 ListableBeanFactory 接口和 Spring Boot Actuator 来列出 Spring IoC 容器中的所有 Bean。