5

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.

5
  • For what it's worth, it's usual with Boot to simply put the resources in a directory static or public in the resources directory and let Boot's default MVC configuration handle registration. You could cut all of this code. Commented Aug 30, 2016 at 16:22
  • is the plugin executed? Can you see it in the output log? Did you define it in build/plugins or build/pluginManagement/plugins? Commented Aug 30, 2016 at 16:23
  • @A_Di-Matteo , i define it in build/plugins, and yeah it works, i can open the jar with winRar and see the static folder in there with all files from webapp folder Commented Aug 30, 2016 at 16:33
  • @chrylis yes, but will i still be able to edit my files without a need to restart the server? Commented Aug 30, 2016 at 16:35
  • That depends on how you launch. I launch from Eclipse with workspace resolution and don't have any problems. Commented Aug 30, 2016 at 16:41

2 Answers 2

8

You should supply multiple resource locations for resolving:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/**").addResourceLocations("/", "classpath:/static/");
}
1
  • 1
    thanks man, this is really useful, i did not even knew, that it was possible to provide multiple locations Commented Aug 30, 2016 at 17:49
0

For me, static resources stop serving up when I add the @EnableWebMvc annotation to the WebMvcConfigurerAdapter class. Without it, it works fine.

Not the answer you're looking for? Browse other questions tagged or ask your own question.