Spring Boot多模块项目中使用WebJars引入Bootstrap失败,求排查建议
让我们一步步排查你的配置问题,大概率是以下几个点导致的:
1. 移除@EnableWebMvc注解(最可能的核心原因)
在Spring Boot中,@EnableWebMvc会直接禁用Spring Boot自带的自动Web MVC配置(也就是WebMvcAutoConfiguration类),而这个自动配置已经帮你做好了WebJars的资源映射——甚至在引入webjars-locator依赖时,还会自动支持不带版本号的资源路径访问。
你的WebConfiguration类添加了@EnableWebMvc,相当于完全接管了Web MVC的配置逻辑,但你手动编写的addResourceHandlers并没有处理webjars-locator的版本自动定位功能,导致请求/webjars/bootstrap/css/bootstrap.min.css时找不到对应资源(实际Jar包内的完整路径是/webjars/bootstrap/4.5.0/css/bootstrap.min.css)。
解决方案:
直接移除@EnableWebMvc注解,同时可以删除手动添加的addResourceHandlers配置,让Spring Boot的自动配置来处理WebJars的映射:
@Configuration // 移除@EnableWebMvc注解 public class WebConfiguration implements WebMvcConfigurer { // 可删除addResourceHandlers方法,或保留用于其他自定义资源映射 }
2. 若需保留手动配置的修正方案
如果你确实需要自定义Web MVC配置(必须保留@EnableWebMvc),那么需要配置WebJarsResourceResolver来支持无版本号的路径访问,修改你的addResourceHandlers方法:
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/") .resourceChain(true) .addResolver(new WebJarsResourceResolver()); }
这里注意资源位置要指向WebJars默认的存放路径classpath:/META-INF/resources/webjars/,同时添加WebJarsResourceResolver来自动解析版本号。
3. 检查Thymeleaf引用路径的兼容性
你当前的Thymeleaf引用写法是正确的,但如果没有webjars-locator的支持,你也可以直接写全版本号来临时验证:
<link th:rel="stylesheet" th:href="@{/webjars/bootstrap/4.5.0/css/bootstrap.min.css}"/> <script th:src="@{/webjars/jquery/3.5.1/jquery.min.js}" type="text/javascript"></script> <script th:src="@{/webjars/bootstrap/4.5.0/js/bootstrap.min.js}" type="text/javascript"></script>
当然,使用webjars-locator+正确配置后,就可以不用写版本号了。
4. 验证依赖是否正确导入
最后确认你的Maven/Gradle已经正确下载了WebJars的依赖包,可以检查项目的依赖库,看是否存在bootstrap-4.5.0.jar、jquery-3.5.1.jar和webjars-locator-0.42.jar。
内容的提问来源于stack exchange,提问作者Syed Iftekharuddin

