SpringBoot中如何查看程序有哪些bean?

SpringBoot中如何查看程序有哪些bean?

在 Spring 中,构成应用程序主干并由Spring IoC容器管理的对象称为bean。所以所谓的Bean管理就是对对象的管理。包含创建对象、给对象注入属性,创建的某一个bean没有启动的问题,就需要进行排查,所以提前了解如何获取以及启动bean,是有好处的,毕竟工作中总是会遇到各种各样的bug。提前了解一些没有坏处。

今日内容介绍,大约花费7分钟

SpringBoot中如何查看程序有哪些bean?

1.IOC容器

Bean是Spring管理应用的基础,所有的bean都在IoC容器中,IOC容器负责管理它们的生命周期。

我们可以通过两种方式获取IOC容器内所有bean的列表:

  • 使用ListableBeanFactory接口获取bean
  • 使用Spring Boot Actuator

2.使用ListableBeanFactory接口获取bean

ListableBeanFactory接口提供了getBeanDefinitionNames()方法,该方法返回在这个工厂中定义的所有bean的名称。

实际上说白了就是使用ApplicationContext获取beans,因为ApplicationContext继承了ListableBeanFactory接口

SpringBoot中如何查看程序有哪些bean?

完整项目结果如下:

SpringBoot中如何查看程序有哪些bean?

创建SpringBoot项目,并创建UserController

@RestController
public class UserController {

    @Autowired
    ApplicationContext applicationContext;

    @GetMapping(value = "/displayallbeans")
    public void getHeaderAndBody() {

        String[] beans = applicationContext.getBeanDefinitionNames();
        for (String beanName : beans) {
            System.out.println("===========================================");
            Class<?> beanType = applicationContext
                    .getType(beanName);
            System.out.println("BeanName:" + beanName);
            System.out.println("Bean的类型:" + beanType);
            System.out.println("Bean所在的包:" + beanType.getPackage());
            System.out.println("Bean:" + applicationContext.getBean(
                    beanName));


            applicationContext.isSingleton(beanName);
        }
    }
}

创建启动类

@SpringBootApplication
public class DisplayAllbeansApplication {
    public static void main(String[] args) {
        SpringApplication.run(DisplayAllbeansApplication.class,args);

    }
}

测试

启动项目,浏览器访问http://localhost:8080/displayallbeans,在控制台打印所有IOC容器中的bean ·SpringBoot中如何查看程序有哪些bean?

注意:我们的方法是获取IOC容器中所有Bean,截图中只是展示我们自己定义的Bean

3.使用Spring Boot Actuator

Spring Boot Actuator提供了用于监控应用程序统计信息的端点,之前文章我也介绍过,大家可以自行前去查看

深入探索Spring Boot Admin

在pom.xml添加actuator依赖

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

在application.yml文件中添加actuator配置

management:
  endpoints:
    web:
      exposure:
        include: '*'

使用“*”可以简化配置成开放所有端点的WEB端HTTP请求权限

测试

重新启动项目,访问http://localhost:8080/actuator查看应用所有端点信息

SpringBoot中如何查看程序有哪些bean?
  • 使用浏览器访问http://localhost:8080/actuator/beans查看IOC容器中所有bean

SpringBoot中如何查看程序有哪些bean?注意:我这边显示的这么正义是因为我添加了JOSN插件JSON-handle,大家可以自行安装

没有安装JSON插件,结果如下

SpringBoot中如何查看程序有哪些bean?

总的来说,本文介绍了如何在Spring IoC容器中的获取bean的两种方法,小伙伴可以根据需求选择适合自己场景的方式。


如果您觉得本文不错,欢迎关注,点赞,收藏支持,您的关注是我坚持的动力!

原创不易,转载请注明出处,感谢支持!如果本文对您有用,欢迎转发分享!


原文始发于微信公众号(springboot葵花宝典):SpringBoot中如何查看程序有哪些bean?

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/202238.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!