Pages

Showing posts with label Springboot. Show all posts
Showing posts with label Springboot. Show all posts

Friday, 14 July 2023

Spring Bean Scopes

 

  • @Bean & @Scope("singleton") or @Bean
  • @Bean & @Scope("prototype")
  • @Bean & @Scope("request") or @Component & @RequestScope
  • @Bean & @Scope("session") or @Component & @SessionScope
  • @Bean & @Scope("application") or @Component & @ApplicationScope
  • @Component & @Scope("websocket")

Tuesday, 15 October 2019

Print all the Spring beans that are loaded - Spring Boot

As shown in the getting started guide of spring-boot: https://spring.io/guides/gs/spring-boot/

@SpringBootApplication
public class Application {

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

  @Bean
  public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
    return args -> {

      System.out.println("Let's inspect the beans provided by Spring Boot:");

      String[] beanNames = ctx.getBeanDefinitionNames();
      Arrays.sort(beanNames);
      for (String beanName : beanNames) {
        System.out.println(beanName);
      }
    };
  }    
}
This will not list manually registered beans.
In case you want to do so, you can use getSingletonNames(). But be careful. This method only returns already instantiated beans. If a bean isn't already instantiated, it will not be returned by getSingletonNames().

Code Review

 SOLID Principles S – Single Responsibility Principle There should never be more than one reason for a class to change. O – Open-Closed Prin...