Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot project with static content generates 404 when running jar

The recent blog post (https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot) by Spring regarding the use of static web content in Spring Boot projects indicates that several resource directories may be used:

  • /META-INF/resources/
  • /resources/
  • /static/
  • /public/

This is thanks to the WebMvcAutoConfiguration class which automatically adds these directories to the classpath. This all seems fine and appears to work when using the spring-boot-maven-plugin spring-boot:run goal, all of your static content is working (eg: /index.html).

When you package your Spring Boot project and allow the spring-boot-maven-plugin to create the enhanced JAR then attempt to run your project using java -jar my-spring-boot-project.jar you find that your static content now returns a 404 error.

like image 888
Robert Hunt Avatar asked Jan 26 '14 01:01

Robert Hunt


2 Answers

It turns out that whilst Spring Boot is being clever at adding the various resource directories to the classpath, Maven is not and it's up to you to deal with that part. By default, only src/main/resources will be included in your JAR. If you create a folder called /static in the root of your project (as implied by the blog post) then it will work fine whilst using the spring-boot:run Maven goal but not once you create a JAR.

The easiest solution is to create your /static folder inside /src/main/resources and then Maven will include it in the JAR. Alternative you can add additional resource locations to your Maven project:

<resources>     <resource>         <directory>src/main/resources</directory>     </resource>     <resource>         <directory>static</directory>         <targetPath>static</targetPath>     </resource> </resources> 

I hope this is useful to someone, it's kind of obvious when you step back and look at how Maven works but it might stump a few people using Spring Boot as it's designed to be pretty much configuration free.

like image 73
Robert Hunt Avatar answered Sep 20 '22 11:09

Robert Hunt


I am banging my head against the wall trying to figure out how to do this with gradle. Any tips?

EDIT: I got it to work by adding this to my build.gradle:

// Copy resources into the jar as static content, where Spring expects it. jar.into('static') {     from('src/main/webapp') } 
like image 44
kgreenek Avatar answered Sep 16 '22 11:09

kgreenek