You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring应用启动报错:无法创建'resourceHandlerMapping' Bean

解决Spring应用启动时No ServletContext set异常的方案

首先咱们拆解下你遇到的核心问题:
你同时加载了JPA配置类(JpaConfiguration)和Spring MVC配置类(WebAppMvcConfigurer),但启动时抛出了IllegalStateException: No ServletContext set。这个异常的根源是:带有@EnableWebMvc的WebAppMvcConfigurer会触发Spring MVC相关Bean(比如resourceHandlerMapping)的创建,而这些Bean必须依赖ServletContext对象;但你用普通的AnnotationConfigApplicationContext启动应用时,这个上下文并没有初始化ServletContext。


正确解决方案:使用Web专用上下文启动应用

你需要切换到Web专用的Spring上下文,并搭配嵌入式Web服务器(比如Tomcat)启动,这样既能初始化ServletContext满足WebMvc的需求,又能正常加载JPA配置。修改App类的main方法如下:

package com.bnpp.creditauto;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

@Configuration
@ComponentScan
public class App {
    public static void main(String[] args) {
        // 创建Web专用的Spring上下文
        AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
        webContext.register(App.class);

        // 初始化嵌入式Tomcat服务器
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8080); // 可自定义端口

        // 关联Tomcat的ServletContext到Spring上下文
        Context tomcatContext = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
        webContext.setServletContext(tomcatContext.getServletContext());
        webContext.refresh();

        // 注册Spring MVC核心DispatcherServlet
        DispatcherServlet dispatcherServlet = new DispatcherServlet(webContext);
        Tomcat.addServlet(tomcatContext, "dispatcher", dispatcherServlet);
        tomcatContext.addServletMappingDecoded("/*", "dispatcher");

        // 启动服务器并等待请求
        try {
            tomcat.start();
            tomcat.getServer().await();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
    }
}

修改后就能同时满足两个需求:

  • Tomcat提供了ServletContext,解决了resourceHandlerMapping的依赖问题,WebMvc配置正常生效,前端可访问Angular应用并接收JSON
  • JPA配置类被Web上下文扫描加载,数据库操作功能正常

关于你临时方案的解释

你之前尝试的几种临时方案之所以能“部分生效”,本质是避免了同时加载WebMvc和JPA配置:

  • 删除WebAppMvcConfigurer的@Configuration:Spring不会加载这个WebMvc配置类,因此不会触发需要ServletContext的Bean创建,JPA配置正常加载,数据库操作可用,但前端因缺少WebMvc配置无法访问
  • 删除JpaConfiguration的@Configuration:仅加载WebMvc配置,但此时用普通上下文启动理论上仍会报错——你能正常访问前端,大概率是因为运行环境隐含了Web上下文(比如误部署到了Web容器),或者@WebAppConfiguration(仅用于测试类)意外阻止了配置类的加载,导致WebMvc配置未被真正初始化

内容的提问来源于stack exchange,提问作者Brice B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:55:47