4

So I just wanted to print all the beans that have been loaded, and I understand the getBeanDefinitionNames() method is what a lot of people suggest. For this I understand you need an ApplicationContext which I autowired as below, but I am getting a null pointer exception on the object when I call getBeanDefinitionNames() on it:

package hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

public class BeansPrinter 
{
    @Autowired
    private ApplicationContext appContext;

    public void printBeans()
    {
        System.out.println("Number of beans:");
        System.out.println(appContext.getBeanDefinitionCount());

        String[] names = appContext.getBeanDefinitionNames();
        for(String name : names)
        {
            System.out.println("-----------------");
            System.out.println(name);
        }
    }
}

Application.java

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);

        BeansPrinter b = new BeansPrinter();
        b.printBeans();
    }
}
rawa
  • 315
  • 3
  • 8
  • 20

1 Answers1

8

BeansPrinter is not a spring bean. The Autowiring will only work if the parent is a spring bean.

Annotate your BeansPrinter with @Component or @Service

@Service("beansPrinter")
public class BeansPrinter 

and in your main class you could do something like:

 ApplicationContext ctx = SpringApplication.run(Application.class, args);

and then ctx.getBean("beansPrinter") to get your bean

6ton
  • 4,174
  • 1
  • 22
  • 37