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

WEB-INF/web.xml存在却提示不存在的Spring依赖异常求助

解决Spring启动时找不到WEB-INF/web.xml的异常

问题场景

web.xml已放置在WEB-INF/web.xml路径下,但Spring应用启动时抛出如下异常:

2022-11-16 17:40:56.120  WARN 3272 --- [main] s.c.a.AnnotationConfigApplicationContext : 
Exception encountered during context initialization - cancelling refresh
attempt: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'securityConfiguration': Unsatisfied
dependency expressed through field 'webXmlRolesParser'; nested exception
is org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'webXmlRolesParser' defined in class path resource
[by/belinvest/panel/admin/config/SecurityConfiguration.class]: Invocation
of init method failed; nested exception is java.io.FileNotFoundException:
class path resource [WEB-INF/web.xml] cannot be opened because it does not exist

解决方案

  • 校验项目资源路径
    确保web.xml位于标准Web应用目录:src/main/webapp/WEB-INF/web.xml,不要放在src/main/resources或其他非Web资源目录。Maven/Gradle默认只会将src/main/webapp下的资源打包到war包根目录,其他位置的WEB-INF不会被正确识别。

  • 修正资源加载逻辑
    若代码中使用ClassPathResource("WEB-INF/web.xml")加载文件,这种方式是从classpath根目录查找,但WEB-INF在war包中不属于classpath范围(jar包启动时更不会被包含)。建议改用ServletContextResource通过Servlet上下文获取真实路径:

    @Autowired
    private ServletContext servletContext;
    
    @PostConstruct
    public void initWebXmlParser() {
        Resource webXmlResource = new ServletContextResource(servletContext, "/WEB-INF/web.xml");
        // 执行文件读取解析逻辑
    }
    
  • 调整项目打包方式
    如果是Spring Boot项目,默认打包为jar,jar包结构不会包含WEB-INF目录。需将打包方式改为war,在pom.xml中配置:

    <packaging>war</packaging>
    

    同时确保启动类继承SpringBootServletInitializer,保证war包可正常启动:

    @SpringBootApplication
    public class AdminPanelApplication extends SpringBootServletInitializer {
        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            return application.sources(AdminPanelApplication.class);
        }
    
        public static void main(String[] args) {
            SpringApplication.run(AdminPanelApplication.class, args);
        }
    }
    
  • 检查IDE部署配置
    在IDEA/Eclipse中,确认src/main/webapp目录被标记为Web资源目录:

    • IDEA:右键webapp目录 → Mark Directory as → Web Resource Directory
    • Eclipse:右键项目 → Properties → Deployment Assembly,确保src/main/webapp被映射到/路径

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 21:25:17