【问题标题】:Unable to serve static resources with Spring Boot无法使用 Spring Boot 提供静态资源
【发布时间】:2018-05-27 05:34:29
【问题描述】:

我有一个具有以下结构的 Sprint Boot Gradle 应用程序:Screenshot of project structure

项目结构

/build.gradle
/src/main/resources/static/css/default.css
/src/main/java/com/expensalyze/ExpensalyzeApplication.java
/src/main/java/com/expensalyze/web/TagController.java

基本上我的 css 文件位于 src/main/resources/static/css/default.css。我希望通过http://localhost:8080/css/default.css 获取此文件。

根据this linkspring boot docs,只需上述设置即可。但是当我尝试访问 http://localhost:8080/css/default.css

时,我得到了 404

build.gradle

plugins {
    id 'java'
    id 'org.springframework.boot' version '2.0.2.RELEASE'
}

repositories {
    mavenCentral()
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web:2.0.2.RELEASE')
}

ExpensalyzeApplication.java

@SpringBootApplication
@EnableWebMvc
@ComponentScan(basePackages = "com.expensalyze")
public class ExpensalyzeApplication {
    public static void main(String[] args) {
        SpringApplication.run(ExpensalyzeApplication.class, args);
    }
}

TagController.java

@Controller
public class TagController {
    @RequestMapping("/tag") // This works properly
    @ResponseBody
    String tag() {
        return "tag";
    }
}
  • 我没有添加任何显式的资源映射配置代码。
  • 我的控制器方法映射工作正常

可以在 here 分支 static-res-test 中找到重现该问题的最低限度代码。您可以通过以下步骤运行项目(需要 JDK 8):

$ ./gradlew clean build
$ java -jar build/libs/expensalyze.jar

如果您访问http://localhost:8080/tag,它可以工作,但如果您访问http://localhost:8080/css/default.css,则找不到!

我错过了什么?

【问题讨论】:

  • 永远不要在启动应用中使用 EnableWebMvc。它删除了 Spring boot 完成的所有 MVC 自动配置,让您掌控一切。 docs.spring.io/spring-boot/docs/current/reference/htmlsingle/…
  • @JBNizet 是的,在 Boot Docs 中搜索(现在)@EnableWebMvc,我发现它会完全按照您所说的进行!我没有彻底阅读文档以理解这一点。感谢您指出了这一点。删除该注释解决了该问题。请添加您的评论作为答案,以便我接受。

标签: java spring-boot gradle


【解决方案1】:

永远不要在启动应用中使用 EnableWebMvc。它删除了 Spring boot 和 puts you in charge of everything 完成的所有 MVC 自动配置。

【讨论】:

    猜你喜欢
    • 2016-05-04
    • 2017-06-01
    • 2017-02-21
    • 1970-01-01
    • 2021-10-11
    • 2016-10-01
    • 2018-11-12
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多