Dmitrij Kostyushko Dmitrij Kostyushko - 3 months ago 18
Java Question

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.

Answer

You should supply multiple resource locations for resolving:

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