Search code examples
javaspringmavenspring-mvcspring-boot

Spring boot app does not serve static resources after packaging into jar


I have a application that work perfectly fine when started via IDE or command line: mvn spring-boot:run. But when I package it into jar, I cannot access static resources(404 not found). I did not want to store static files in resource fouler so I don`t have to reload the server each time I need to change static file. So I used this plugin in my pom.xml:

<plugin>
  <artifactId>maven-resources-plugin</artifactId>
  <version>2.6</version>
  <executions>
    <execution>
      <id>copy-resources</id>
      <phase>validate</phase>
      <goals>
        <goal>copy-resources</goal>
      </goals>
      <configuration>
        <outputDirectory>${basedir}/target/classes/static</outputDirectory>
        <resources>
          <resource>
            <directory>src/main/webapp</directory>
            <filtering>true</filtering>
          </resource>
        </resources>
      </configuration>
    </execution>
  </executions>
</plugin>

I can see that files are being copied in two the directory "static". This is my configuration of resource handler:

  @Configuration
  @EnableWebMvc
  public class WebMvcConfig extends WebMvcConfigurerAdapter {
    
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/**").addResourceLocations("/");
  }

Controllers RequestMappings are working fine, problems are only with the static resources.


Solution

  • You should supply multiple resource locations for resolving:

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("/", "classpath:/static/");
    }