Spring Boot 如何获取Web应用上下文中的所有Bean
Spring Boot 获取Web应用上下文所有Bean的实现方案
Spring Boot 项目中 WebApplicationContext 是普通ApplicationContext的子类,针对Web场景做了扩展,你可以通过以下三种常用方式获取Web上下文并遍历所有Bean:
方案1:直接注入WebApplicationContext
在任意被Spring管理的Bean(Controller、Service、自定义Component等)中,直接通过@Autowired注入WebApplicationContext实例即可调用API获取所有Bean:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.context.WebApplicationContext; @Component public class WebBeanQueryUtil { @Autowired private WebApplicationContext webApplicationContext; /** * 打印Web上下文中的所有Bean信息 */ public void printAllWebBeans() { // 获取所有Bean的名称 String[] beanDefinitionNames = webApplicationContext.getBeanDefinitionNames(); for (String beanName : beanDefinitionNames) { Object beanInstance = webApplicationContext.getBean(beanName); System.out.printf("Bean名称:%s,Bean类型:%s%n", beanName, beanInstance.getClass().getName()); } } }
如果需要筛选Web上下文特有的Bean,可判断Bean类型是否属于org.springframework.web包下的类即可。
方案2:通过ServletContext获取
在Servlet相关的请求处理场景中,可通过WebApplicationContextUtils工具类从ServletContext中提取Web上下文:
import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.http.HttpServletRequest; // 示例:在Controller的请求方法中获取 public void queryBeans(HttpServletRequest request) { WebApplicationContext webContext = WebApplicationContextUtils .getRequiredWebApplicationContext(request.getServletContext()); String[] allBeanNames = webContext.getBeanDefinitionNames(); // 自定义遍历逻辑 }
方案3:项目启动时直接获取
Spring Boot Web项目启动后返回的ConfigurableApplicationContext本身就是WebApplicationContext的实现类,可直接强转后使用:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.web.context.WebApplicationContext; @SpringBootApplication public class WebDemoApplication { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(WebDemoApplication.class, args); // 校验上下文类型后强转 if (context instanceof WebApplicationContext webContext) { String[] allBeans = webContext.getBeanDefinitionNames(); System.out.println("Web应用上下文总Bean数量:" + allBeans.length); } } }
补充说明:传统Spring MVC项目会存在父上下文、Web子上下文的分层结构,需要单独获取Web子上下文才能拿到Web相关Bean;但Spring Boot默认没有分层设计,普通
ApplicationContext和WebApplicationContext拿到的是同一批Bean,你之前的普通上下文获取方案也可以直接复用。
内容的提问来源于stack exchange,提问作者Vaishu13
相关产品推荐
相关产品推荐

