16

I am using Netbeans and I am developing my first web application using spring boot. I was keeping my HTML, js, CSS in "webapp" folder and then I refactored my project and I put all static content in /resources/static. Since then, I have to rebuild my project every time because the static content isn't reloaded.

Can I easily bypass this problem if I'll use browser-sync plugin for Gulp?

Dilan Tharaka
  • 517
  • 5
  • 15
Claude
  • 210
  • 1
  • 3
  • 10

3 Answers3

48

Add the following to src/main/resources/application.properties:

spring.web.resources.static-locations[0]=file:src/main/resources/static/
spring.web.resources.static-locations[1]=classpath:/static/

The "file:" causes the content to be reloaded on refreshing the browser, see related issue.

Alternatively, the file resource locations can be discovered at runtime and added programmatically.

See also documentation and tutorial.

Note that prior to Spring Boot 2.4, the property was called "spring.resources.static-locations".

AlexO
  • 1,311
  • 12
  • 18
  • I also had to remove my registry.addResourceHandler().addResourceLocations() from method addResourceHandlers in WebMvcConfigurer interface, otherwise i only could get the content if the directory was already created by the application. Now it´s working, thanks for this black magik – Hinotori Apr 25 '20 at 21:04
  • 3
    Just an update - it's now `spring.web.resources.static-locations` instead of `spring.resources.static-locations` – Zach Feb 13 '21 at 19:39
  • 1
    Similarly, for loading Thymeleaf templates directly from the source directory in development, instead of the default `classpath:/templates/`, set `spring.thymeleaf.prefix=file:src/main/resources/templates/` – Dario Seidl May 26 '23 at 13:59
2

if an application.yml file is used for configuration, insert:

spring:
  web:
    resources:
      static-locations[0]: "file:src/main/resources/static/"
      static-locations[1]: "classpath:/static/"
Jundl
  • 3,084
  • 3
  • 15
  • 16
  • 2
    note that in yaml the [n] suffix is not necessary, you can specify 'static-locations' as a map key and then the two strings can be list items (indicated by "- ") – AlexO Jul 13 '21 at 18:49
  • Hi, do these indexes [0] and [1] indicate the hierarchy of files? If the file is found in the [0] location, it is loaded; otherwise, the [1] location is checked, and so on? – Mike U Aug 07 '23 at 07:21
1

Normally the static content is copied to the build directory ( target if you are using maven) by the spring-boot plugin. You can find your files at {build-directory}/classes/static: These are the files that you should modify to reflect changes. You should also copy your changes to resources/static, because whenever you restart spring boot, the files are copied.

zakaria amine
  • 3,412
  • 2
  • 20
  • 35