Newsletter |
Spring Boot – Display All Beans Available in ApplicationContext
In this article, I am going to show you how to see the beans that are loaded by the Spring Boot from the ApplicationContext. What we have to do is implement main class with CommandLineRunner/ApplicationRunner interface and override its run method.
CommandLineRunner/ApplicationRunner’s run() method will get execute right after ApplicationContext is created and before Spring Boot application initialized. This run() method will execute only once in an application’s life cycle. So what’s the difference between CommandLineRunner/ApplicationRunner? Basically, both will do the same trick, the only difference is CommandLineRunner’s run() method will accept String array and ApplicationRunner’s run() will accept ApplicationArguments as arguments.
SpringBootApp.java
package com.java4s.app; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; @SpringBootApplication public class SpringBootApp implements CommandLineRunner { @Autowired private ApplicationContext context; public static void main(String[] args) { SpringApplication.run(SpringBootApp.class, args); } @Override public void run(String...args) throws Exception { String[] beans = context.getBeanDefinitionNames(); for (String bean: beans) { System.out.println(bean); } } }
Output
Run the application and you will be able to see all the beans available in the context, here I am just adding few bean names from my console 😉
... org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration requestMappingHandlerAdapter requestMappingHandlerMapping mvcValidator mvcContentNegotiationManager mvcPathMatcher mvcUrlPathHelper viewControllerHandlerMapping beanNameHandlerMapping resourceHandlerMapping mvcResourceUrlProvider defaultServletHandlerMapping mvcConversionService mvcUriComponentsContributor httpRequestHandlerAdapter simpleControllerHandlerAdapter handlerExceptionResolver mvcViewResolver ... ....
Give a try by downloading and executing this application in your local 🙂
You Might Also Like
::. About the Author .:: | ||
Hi, Could you please provide tutorials in micro services and dockers.
No need to implement CommandLineRunner. Context object is available in the entire application.
Hello Teja,
I am naveen.I am very big fan of you.Please update a post on Authorization and Authentication in real rime .Please support with this post