Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4536

How to Get All Spring-Managed Beans?

$
0
0

1. Overview

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

2. The IoC Container

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.

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

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

3. Using ListableBeanFactory Interface

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.

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.

First, we’ll create some Spring beans. Let’s create a simple Spring 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";
    }
}

This Controller is dependent on another 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:

  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:

@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:

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.

4. Using Spring Boot Actuator

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

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.

Now we’ll configure our beans endpoint in our application.properties:

endpoints.beans.id=springbeans
endpoints.beans.sensitive=false

Here, we’re setting id of bean endpoint. This springbeans id will now be mapped to a URL which will be used to access it over HTTP. We’ve set the sensitive property to false so that we can access it without authentication. We can leave it to default value true if we want only authenticated users to see the data.

Now, we’ll just hit the URL http://<address>:<management-port>/springbeans. 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:

[
    {
        "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.

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

5. Conclusion

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

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


Viewing all articles
Browse latest Browse all 4536

Trending Articles