关于java:Springboot启动了哪些bean这两种方式可以获取

2次阅读

共计 2142 个字符,预计需要花费 6 分钟才能阅读完成。

1. 概述


在本文中,咱们将摸索在容器中获取所有 spring 治理的 bean 的相干技术。这有神马用?次要是用于排查问题。个别都是咱们创立的某一个 bean 没有启动的问题。毕竟工作中总是会遇到各种各样的 bug。提前理解一些没有害处。

2. IoC 容器


bean 是 spring 治理的应用程序的根底,所有 bean 都驻留在 IOC 容器中,该容器负责管理它们的生命周期。

咱们能够通过两种形式获取该容器内所有 bean 的列表:

  1. 应用_ListableBeanFactory_接口
  2. 应用 Spring Boot Actuator

3. 应用 ListableBeanFactory 接口

ListableBeanFactory 接口提供了 getBeanDefinitionNames() 办法,该办法返回在这个工厂中定义的所有 bean 的名称。您能够在官网文档中找到所有已知子接口及其实现类的列表。咱们来看这种形式如何获取所有的 bean。

第一步:创立一个 Controller

`@Controller
public class FooController {
    @Autowired
    private FooService fooService;
    @RequestMapping(value=”/displayallbeans”)
    public String getHeaderAndBody(Map model){
        model.put(“header”, fooService.getHeader());
        model.put(“message”, fooService.getBody());
        return “displayallbeans”;
    }
}
`

这个 Controller 依赖于另一个 FooService。

第二步:创立 Service

`@Service
public class FooService {
    public String getHeader() {
        return “Display All Beans”;
    }
    public String getBody() {
        return “ 展现所有 beans 的案例 ”;
    }
}
`

留神,咱们在这里创立了两个不同的 bean:

  • fooController
  • fooService

这里应用 applicationContext 对象并调用它的 getBeanDefinitionNames() 办法,该办法将返回 applicationContext 容器中的所有 bean:

第三步:设置 SpringBootApplication 启动类

`@SpringBootApplication
public class DemoApplication {
    private static ApplicationContext applicationContext;
    public static void main(String[] args) {
        applicationContext = SpringApplication.run(DemoApplication.class, args);
        displayAllBeans();
    }
    public static void displayAllBeans() {
        String[] allBeanNames = applicationContext.getBeanDefinitionNames();
        for(String beanName : allBeanNames) {
            System.out.println(beanName);
        }
    }
}
`

第四步:测试打印

这将打印 applicationContext 容器中的所有 bean:

留神,除了咱们定义的 bean 之外,它还将记录该容器中的所有其余 bean。为了分明起见,咱们在这里省略了它们,因为它们有很多。

4. 应用 Spring Boot Actuator


Spring Boot Actuator 提供了用于监控应用程序统计信息的端点。上面看看这种形式:

第一步:增加依赖

`<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
`

第二步:批改 application.properties

management.endpoints.web.exposure.include=*

把下面代码增加到 properties 文件中。

第三步:应用公布端点查看

因为这里的 Actuator 没有配置,所以显示的比拟乱。对于 Actuator 的配置,会在下一篇文章中出现。

5. 论断


在本文中,咱们理解了如何应用 ListableBeanFactory 接口和 Spring Boot Actuator 在 Spring IoC 容器中显示所有 bean。心愿对你有点帮忙。

正文完
 0