传统Servlet容器集成Spring依赖注入需通过ContextLoaderListener加载根WebApplicationContext,并在web.xml中配置;Service等非Web层Bean定义于applicationContext.xml,Controller等Web层Bean由DispatcherServlet子上下文管理,实现层级隔离与依赖注入。

在传统 Servlet 容器(如 Tomcat、Jetty)中集成 Spring 的依赖注入功能,核心是让 Spring 容器启动并接管 Bean 的生命周期,同时与 Servlet 规范协同工作。这通常通过 Spring 的 WebApplicationContext 和 ContextLoaderListener 实现,而非直接使用 Spring Boot 的自动配置。
1. 添加 Spring Web 依赖
确保项目包含 Spring Web 模块(非 Spring Boot):
- Maven 中引入
spring-web(版本需与 Spring 核心一致,如 5.3.x 或 6.1.x) - 避免混用 Spring Boot starter(除非你用的是 Spring Boot 的 war 部署模式)
2. 配置 web.xml 启动 Spring 容器
在 WEB-INF/web.xml 中注册监听器,加载根应用上下文:
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
其中 applicationContext.xml 是 Spring 的 XML 配置文件,用于定义 Service、DAO 等非 Web 层 Bean;它由 ContextLoaderListener 加载为根 WebApplicationContext。
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
立即学习“Java免费学习笔记(深入)”;
3. 在 Servlet 或 Filter 中获取 Spring Bean
Servlet 容器本身不管理 Spring Bean,但可通过 WebApplicationContextUtils 获取上下文并提取 Bean:
- 在自定义
HttpServlet的init()方法中获取上下文:WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); - 再调用
ctx.getBean(MyService.class)注入依赖 - 更推荐的方式:让 Servlet 实现
ApplicationContextAware,或继承HttpServletBean(Spring 提供的基类),实现自动注入
4. 可选:用 DispatcherServlet 管理 Controller 层
若需 Spring MVC 功能(如 @Controller、@RequestMapping),还需配置前端控制器:
- 在
web.xml中声明DispatcherServlet - 为其指定独立的配置文件(如
dispatcher-servlet.xml),通常只放@Controller、视图解析器等 Web 相关 Bean - 注意:该 Servlet 的上下文默认是根上下文的子容器,可访问根容器中的 Service Bean,但反之不行
不复杂但容易忽略的是上下文层级关系和作用域隔离——Service 层 Bean 放在根上下文,Controller 放在子上下文,这样既解耦又支持依赖注入。

















