无法使用Spring Boot提供静态资源

时间:2018-05-27 05:34:30

标签: java spring-boot gradle

我有一个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 link以及spring 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";
    }
}
  • 我没有添加任何显式的资源映射配置代码。
  • 我的控制器方法映射正常工作

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

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

如果您访问http://localhost:8080/tag它有效,但是如果您访问http://localhost:8080/css/default.css则找不到它!

我错过了什么?

1 个答案:

答案 0 :(得分:1)

不要在启动应用中使用EnableWebMvc。它删除了Spring引导完成的MVC的所有自动配置,以及puts you in charge of everything

相关问题