How to Get All Spring-Managed Beans? – 如何获得所有Spring管理的Bean?

最后修改: 2017年 6月 14日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this article, we’ll explore different techniques for displaying all Spring-managed beans withing the container.

在这篇文章中,我们将探讨在容器中显示所有Spring管理的bean的不同技术。

2. The IoC Container

2.IoC容器

A bean is the foundation of a Spring-managed application; all beans reside withing the IOC container, which is responsible for managing their life cycle.

Bean是Spring管理的应用程序的基础;所有的Bean都驻扎在IOC容器中,IOC容器负责管理它们的生命周期。

We can get a list of all beans within this container in two ways:

我们可以通过两种方式获得这个容器内所有Bean的列表。

  1. Using a ListableBeanFactory interface
  2. Using a Spring Boot Actuator

3. Using ListableBeanFactory Interface

3.使用ListableBeanFactory 接口

The ListableBeanFactory interface provides getBeanDefinitionNames() method which returns the names of all the beans defined in this factory. This interface is implemented by all the bean factories that pre-loads their bean definitions to enumerate all their bean instances.

ListableBeanFactory接口提供了getBeanDefinitionNames()方法,该方法返回该工厂中定义的所有Bean的名称。这个接口由所有预先加载其Bean定义的Bean工厂实现,以列举其所有Bean实例。

You can find the list of all known subinterfaces and its implementing classes in the official documentation.

你可以在官方文档中找到所有已知子接口及其实现类的列表。

For this example, we’ll be using a Spring Boot Application.

在这个例子中,我们将使用一个Spring Boot应用程序。

First, we’ll create some Spring beans. Let’s create a simple Spring Controller FooController:

首先,我们要创建一些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";
    }
}

This Controller is dependent on another Spring bean FooService:

这个控制器依赖于另一个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.";
    }
}

Note that we’ve created two different beans here:

请注意,我们在这里创建了两个不同的Bean。

  1. fooController
  2. fooService

While executing this application, we’ll use applicationContext object and call its getBeanDefinitionNames() method, which will return all the beans in our applicationContext container:

在执行这个应用程序时,我们将使用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);
        }
    }
}

This will print all the beans from applicationContext container:

这将打印applicationContext容器中的所有bean。

fooController
fooService
//other beans

Note that along with beans defined by us, it will also log all other beans that are in this container. For the sake of clarity, we’ve omitted them here because there are quite a lot of them.

请注意,除了我们定义的Bean,它还会记录这个容器中的所有其他Bean。为了清楚起见,我们在这里省略了它们,因为它们的数量相当多。

4. Using Spring Boot Actuator

4.使用Spring Boot Actuator

The Spring Boot Actuator functionality provides endpoints which are used for monitoring our application’s statistics.

Spring Boot Actuator功能提供了端点,用于监控我们应用程序的统计数据。

It includes many built-in endpoints, including /beans. This displays a complete list of all the Spring managed beans in our application. You can find the full list of existing endpoints over on the official docs.

它包括许多内置端点,包括/beans。这将显示我们应用程序中所有Spring管理的Bean的完整列表。您可以在官方文档上找到现有端点的完整列表

 

Now, we’ll just hit the URL http://<address>:<management-port>/beans. We can use our default server port if we haven’t specified any separate management port. This will return a JSON response displaying all the beans within the Spring IoC Container:

现在,我们只需点击URL http://< address>:<management-port>/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": []
            },
            // ...other beans
        ]
    }
]

Of course, this also consists of many other beans that reside in the same spring container, but for the sake of clarity, we’ve omitted them here.

当然,这也包括居住在同一个Spring容器中的许多其他Bean,但为了清楚起见,我们在这里省略了它们。

If you want to explore more about Spring Boot Actuators, you can head on over to the main Spring Boot Actuator guide.

如果您想探索有关Spring Boot执行器的更多信息,您可以前往主Spring Boot执行器指南。

5. Conclusion

5.结论

In this article, we learned about how to display all beans in a Spring IoC Container using ListableBeanFactory interface and Spring Boot Actuators.

在这篇文章中,我们了解了如何使用ListableBeanFactory接口和Spring Boot Actuators来显示Spring IoC Container中的所有bean。

The full implementation of this tutorial can be found over on Github.

本教程的完整实现可以在Github上找到