user9530236
user9530236

Reputation:

Unable to serve static resources with Spring Boot

I have a Sprint Boot Gradle application that has the following structure: Screenshot of project structure

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

Basically I have my css file located at src/main/resources/static/css/default.css. I am expecting to fetch this file at http://localhost:8080/css/default.css.

As per this link and also the spring boot docs, the above setup is all that's needed. But I am getting a 404 when I try to visit 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";
    }
}

The bare minimum code to reproduce the issue can be found here in the branch static-res-test. You can run the project with these steps (requires JDK 8):

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

If you visit http://localhost:8080/tag it works, but if you visit http://localhost:8080/css/default.css it is not found!

What am I missing?

Upvotes: 0

Views: 518

Answers (1)

JB Nizet
JB Nizet

Reputation: 691725

Don't, ever, use EnableWebMvc in a Boot app. It removes all the autoconfiguration of MVC done by Spring boot, and puts you in charge of everything.

Upvotes: 1

Related Questions