获取所有spring管理的bean
本文我们探索使用不同的方式获取spring容器中所有bean。
IOC容器
bean是基于spring应用的基础,所有bean都驻留在ioc容器中,由容器负责管理bean生命周期
有两种方式可以获取容器中的bean:
- 使用ListableBeanFactory接口
- 使用Spring Boot Actuator
使用ListableBeanFactory接口
ListableBeanFactory接口提供了getBeanDefinitionNames() 方法,能够返回所有定义bean的名称。该接口被所有factory实现,负责预加载bean定义去枚举所有bean实例。官方文档提供所有其子接口及其实现。
下面示例使用Spring Boot 构建:
首先,我们创建一些spring bean,先定义简单的Controller 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";
}
}
该Controller依赖另一个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:
- fooController
- fooService
现在我们运行该应用。使用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
//other beans
需注意除了我们定义的bean外,它还将打印容器中所有其他bean。为了清晰起见,这里省略了很多。
使用Spring Boot Actuator
Spring Boot Actuator提供了用于监视应用程序统计信息的端点(endpoint)。除了/beans
,还包括很多其他端点,官方文档有详细说明。
现在我们访问url: http//
:/beans,如果没有指定其他独立管理端口,我们使用缺省端口,结果会返回json,包括容器所有定义的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": []
},
// ...other beans
]
}
]
当然,结果同样包括很多其他的bean,为了简单起见,这里没有列出。
总结
本文我们介绍了使用ListableBeanFactory 接口和 Spring Boot Actuators 返回spring 容器中所有定义的bean信息。
本文参考链接:https://blog.csdn.net/neweastsun/article/details/80464893