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

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

1.IOC容器

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

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

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

2.使用ListableBeanFactory接口获取bean

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

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

图片[1]-SpringBoot中如何查看程序有哪些bean-不念博客

完整项目结果如下:

图片[2]-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 ·

图片[3]-SpringBoot中如何查看程序有哪些bean-不念博客

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

3.使用Spring Boot Actuator

在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查看应用所有端点信息

图片[4]-SpringBoot中如何查看程序有哪些bean-不念博客
  • 使用浏览器访问http://localhost:8080/actuator/beans查看IOC容器中所有bean
图片[5]-SpringBoot中如何查看程序有哪些bean-不念博客

注意:我这边显示的这么正义是因为我添加了JOSN插件JSON-handle,大家可以自行安装

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

图片[6]-SpringBoot中如何查看程序有哪些bean-不念博客

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

© 版权声明
THE END
喜欢就支持一下吧
点赞117赞赏 分享
评论 抢沙发
头像
欢迎光临不念博客,留下您的想法和建议,祝您有愉快的一天~
提交
头像

昵称

取消
昵称

    暂无评论内容