• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

如何获取所有spring管理的bean

java 搞代码 4年前 (2022-01-09) 33次浏览 已收录 0个评论
文章目录[隐藏]

获取所有spring管理的bean

本文我们探索使用不同的方式获取spring容器中所有bean。

IOC容器

bean是基于spring应用的基础,所有bean都驻留在ioc容器中,由容器负责管理bean生命周期

有两种方式可以获取容器中的bean:

– 使用ListableBeanFactory接口

– 使用Spring Boot Actuator

使用ListableBeanFactory接口

ListableBeanFactory接口提供了getBeanDefinitionNames() 方法,能够返回所有定义bean的名称。该接口被所有factory实现,负责预加载bean定义去枚举所有bean实例。官方文档提供所有其子接口及其实现。

下面示例使用Spring Boot 构建:

首先,我们创建一些spring bean,先定义简单的Controller FooController:

@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依赖另一个spring Bean FooService:

@Service
public class FooService {
    public String getHeader() {
        return "Display All Beans";
    }
    public String getBody() {
        return "This is a sample application that displays all beans "
          + "in Spring IoC container <b>本文来源gao@dai!ma.com搞$代^码!网7</b>using ListableBeanFactory interface "
          + "and Spring Boot Actuators.";
    }
}

我们创建了两个不同的bean:

1.fooController

2.fooService

现在我们运行该应用。使用applicationContext 对象调用其 getBeanDefinitionNames() 方法,负责返回applicationContext上下文中所有bean。

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

会输出applicationContext上下文中所有bean:

fooController

fooService

//other beans

需注意除了我们定义的bean外,它还将打印容器中所有其他bean。为了清晰起见,这里省略了很多。

使用Spring Boot Actuator

Spring Boot Actuator提供了用于监视应用程序统计信息的端点(endpoint)。除了/beans,还包括很多其他端点,官方文档有详细说明。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:如何获取所有spring管理的bean

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址