如何在 Spring Boot 中获取所有加载的 Bean

x33g5p2x  于2022-09-29 转载在 Spring  
字(3.6k)|赞(0)|评价(0)|浏览(1345)

在本教程中,我们将展示如何找出 Spring Boot Application 类加载的所有 Bean 及其类类型信息。

使用 ApplicationContext获取所有加载的 Bean

ApplicationContext 是 Spring 应用程序在需要向应用程序检索配置信息时的主界面。它在运行时是只读的,但可以在必要时重新加载并由应用程序支持。为此,可以使用以下方法:

  1. ApplicationContext.getBeanDefinitionNames() 查找所有加载的bean的名称
  2. ApplicationContext.getBean(beanName) 获取包含其运行时类型信息的 bean。

这是我们的 JPA 基本应用程序的扩展版本(请参阅 Using SpringBoot with JPA 教程),它使用 ApplicationContext 打印出 Bean 信息:

package com.example.samplewebapp;
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;
import org.springframework.context.annotation.Bean;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SpringBootApplication public class DemoApplication {
  private static final Logger log = LoggerFactory.getLogger(DemoApplication.class);
  @Autowired private ApplicationContext appContext;
  public void dumpBeans() {
    String[] beans = appContext.getBeanDefinitionNames();
    Arrays.sort(beans);
    for (String bean: beans) {
      System.out.println(bean + " of Type :: " + appContext.getBean(bean).getClass());
    }
  }
  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
  @Bean public CommandLineRunner demo(PersonRepository repository) {
    return (args) -> { // save a couple of persons 			
      repository.save(new Person("Jack", "Smith"));repository.save(new Person("Joe", "Black"));repository.save(new Person("Martin", "Bauer"));
      // fetch all persons 			
      log.info("Persons found with findAll():");log.info("-------------------------------");
      for (Person person: repository.findAll()) {
        log.info(person.toString());
      }
      log.info("");
      // fetch an individual person by ID 			
      repository.findById(1 L).ifPresent(person -> {
        log.info("Person found with findById(1L):");log.info("--------------------------------");log.info(person.toString());log.info("");
      });
      // fetch persons by last name
      log.info("Person found with findBySurname('Black'):");log.info("--------------------------------------------");repository.findBySurname("Black").forEach(smith -> {
        log.info(smith.toString());
      });log.info("");dumpBeans();
    };
  }
}

运行上面的应用程序将在控制台中打印 bean 名称和类型信息,如下所示:

applicationTaskExecutor of Type :: class org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
basicErrorController of Type :: class org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController
beanNameHandlerMapping of Type :: class org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping
beanNameViewResolver of Type :: class org.springframework.web.servlet.view.BeanNameViewResolver
characterEncodingFilter of Type :: class org.springframework.boot.web.servlet.filter.OrderedCharacterEncodingFilter
conventionErrorViewResolver of Type :: class org.springframework.boot.autoconfigure.web.servlet.error.DefaultErrorViewResolver
dataSource of Type :: class com.zaxxer.hikari.HikariDataSource
dataSourceInitializedPublisher of Type :: class org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher
dataSourceInitializerPostProcessor of Type :: class org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerPostProcessor
defaultServletHandlerMapping of Type :: class org.springframework.beans.factory.support.NullBean
defaultTemplateResolver of Type :: class org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver
defaultValidator of Type :: class org.springframework.validation.beanvalidation.LocalValidatorFactoryBean
defaultViewResolver of Type :: class org.springframework.web.servlet.view.InternalResourceViewResolver
...

相关文章

微信公众号

最新文章

更多