Java配置下Spring MVC移除WebMvcConfigurerAdapter后静态资源无法加载怎么办
问题根因
你之前RootConfig继承WebMvcConfigurerAdapter相当于在根容器中重复加载了Spring MVC相关配置,和WebConfig上的@EnableWebMvc注解产生配置冲突,才会导致Spring Security项目部署失败。去掉继承后冲突消失,但静态资源无法加载是配置遗漏导致的,可通过以下步骤修复:
解决方案
- 第一步:优化包扫描配置避免Bean重复加载
RootConfig作为根容器配置,仅负责扫描非Controller层的组件,WebConfig作为Servlet容器配置仅负责扫描Controller层,修改两个类的扫描规则:// RootConfig修改为排除Controller扫描 @Configuration @ComponentScan(value = "org.example", excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, value = Controller.class)) public class RootConfig { }// WebConfig修改为仅扫描Controller @Configuration @EnableWebMvc @ComponentScan(value = "org.example", includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, value = Controller.class), useDefaultFilters = false) public class WebConfig implements WebMvcConfigurer { // 原有其他配置保持不变 } - 第二步:在Spring Security配置中放行静态资源
Spring Security默认会拦截所有请求,需要在Security配置类中忽略静态资源路径的校验:@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/resources/**"); } // 其他Security相关配置保持不变 } - 第三步:优化资源处理器配置(可选,兼容更多场景)
可以给资源处理器增加类路径下的静态资源目录兜底,避免路径匹配失败:@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**") .addResourceLocations("/resources/", "classpath:/static/", "classpath:/public/"); } - 第四步:优化JSP静态资源引入写法(可选,更稳定)
改用JSTL的c标签生成资源路径,避免上下文路径识别异常:<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <link rel="stylesheet" href="<c:url value='/resources/css/index.css'/>">
内容的提问来源于stack exchange,提问作者DPilot
相关产品推荐
相关产品推荐

