Print all the Spring beans that are loaded

public class PrintBeans {
    @Autowired
    ApplicationContext applicationContext;

    public void printBeans() {
        System.out.println(Arrays.asList(applicationContext.getBeanDefinitionNames()));
    }
}

With Spring Boot and the actuator starter

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

you can check the endpoint /beans


Print all bean names and its classes:

package com.javahash.spring.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloWorldController {

    @Autowired
    private ApplicationContext applicationContext;

    @RequestMapping("/hello")
    public String hello(@RequestParam(value="key", required=false, defaultValue="World") String name, Model model) {

        String[] beanNames = applicationContext.getBeanDefinitionNames();

        for (String beanName : beanNames) {

            System.out.println(beanName + " : " + applicationContext.getBean(beanName).getClass().toString());
        }

        model.addAttribute("name", name);

        return "helloworld";
    }
}

Yes, get ahold of ApplicationContext and call .getBeanDefinitionNames()

You can get the context by:

  • implementing ApplicationContextAware
  • injecting it with @Inject / @Autowired (after 2.5)
  • use WebApplicationContextUtils.getRequiredWebApplicationContext(..)

Related: You can also detect each bean's registration by registering a BeanPostprocessor bean. It will be notified for each bean.

Tags:

Java

Spring