我有一个 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
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";
}
}
- 我没有添加任何显式资源映射配置代码。
- 我的 Controller 方法映射工作正常
可以找到重现该问题的最低限度代码 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 自动配置,并且 puts you in charge of everything .
关于java - 无法使用 Spring Boot 提供静态资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50549315/