首页 > 解决方案 > Spring Boot 不从 jar 内部提供静态文件

问题描述

Spring Boot 不提供放置在 jar 中的静态文件。

我有一个后端应用程序,我决定添加前端。设置任务以将静态前端文件复制到src/main/resources/static. 在 SO 上经历了一堆答案,他们都建议静态内容(index.html、.js 和 .css 文件)应该驻留在src/main/resources/staticor下src/main/resources/public,我都试过了。我打开构建的 .jar 并且静态文件在那里,但是使用java -jar myApp.jar和打开启动应用程序localhost:8080会给我默认的 whitelabel 错误页面。我的应用程序工作正常,因为我可以访问我在其上运行的 api。应用程序没有@EnableWebMvc或任何其他自定义配置。

如果我手动将相同的静态资源复制/粘贴到项目中src/main/resources/static并使用 IDE 中的 @SpringBootApplication 类运行应用程序 - 资源加载没有问题,并且 index.html 在访问时打开localhost:8080,所以只有文件在 .jar 中时才会出现问题。静态文件在可运行的 spring boot .jar 文件中时是否应该有所不同?Spring Boot 2.1.1 版本

标签: javaspringspring-boot

解决方案


我面临同样的问题。

如果有帮助,我可以通过添加以下配置来正确地提供静态文件:

包 fr.maif.darwin.api.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class StaticFilesConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
}

...但是它覆盖了spring boot的“隐式”自动配置,我的其他过滤器等不再起作用...=>这是因为@EnableWebMvc停用了spring的默认配置。

[编辑]最后,我碰巧了解到包含静态文件的 jar 未包含在构建的 bootJar 中。你可能想检查一下。!


推荐阅读