Wednesday, April 24, 2019

Spring Boot Interview Questions

Q- How to display all beans loaded by spring-boot?

Q- Print all beans loaded by Spring Boot?

Q- How to display count of all beans loaded by spring-boot?

All beans reside withing the IOC container, which is responsible to managing their life cycle.

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

  • Using a ListableBeanFactory interface 
  • Using a Spring Boot Actuator 
 @SpringBootApplication defines an automatic Component Scan on the package.

The ListableBeanFactory interface provides getBeanDefinitionNames() method which returns the name of all the beans defined in this factory.

Approach 1: Using A ListableBeanFactory Interface

package com.shubh.springboot.example

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class SpringBootPrintAllBeansApplication {

    public static void main(String[] args) {
 
        int count=0;
        ApplicationContext applicationContext = 
                          SpringApplication.run(SpringBootPrintAllBeansApplication.class, args);
        System.out.println("Display all loaded beans by spring boot");
        for (String beanName: applicationContext.getBeanDefinitionNames()) {
             System.out.println(beanName);
        }
        System.out.println("Display count of all loaded beans by spring boot");
        count = applicationContext.getBeanDefinitionCount();
        System.out.println(count);
    }
}

    Or    

package com.shubh.springboot.example
import java.util.Arrays;
 
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 SpringBootPrintAllBeansApplication implements CommandLineRunner {
 
 @Autowired
 private ApplicationContext appContext;
 
 public static void main(String[] args) 
 {
  SpringApplication.run(SpringBootPrintAllBeansApplication.class, args);   
 }
 
 @Override
 public void run(String... arg0) throws Exception {
  String[] beansArr = appContext.getBeanDefinitionNames();
  Arrays.sort(beansArr);
  for (String beanName : beansArr) {
   System.out.println(beanName);
  } 
 }
}
 
Approach 2: Spring Boot Actuator  The Spring Boot Actuator provides endpoints which can used to monitoring our application’s statistics.
Actuator has many built-in endpoints, including /beans. This displays a list of all the beans managed in our application. like example : http://loaclhost:8080/projectname/beans  or   http://loaclhost:8080/beans

No comments:

Post a Comment