I’ve been using Spring Boot recently, and it’s great. However, some things are not yet intuitive. For instance, mapping an external directory to the default static resources handling.
The only way I know of, currently, is to provide a custom WebMvcConfigurer. Various examples on the Internet and StackOverflow show how to provide an explicit mapping, but I wanted to extend the built-in WebMvcConfigurer instead of replacing it.
I decided to try extending the Spring Boot WebMvcAutoConfigurationAdapter, and that seems to have worked.
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurerAdapter.class})
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter(DispatcherServletAutoConfiguration.class)
public class CustomWebMvcAutoConfig extends WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String myExternalFilePath = "file:///C:/Temp/whatever/m/";
registry.addResourceHandler("/m/**").addResourceLocations(myExternalFilePath);
super.addResourceHandlers(registry);
}
}
The call to `super.addResourceHandlers` sets up the default handlers.
Also:
- Note the trailing slash on the external file path. (Depends on your expectation for URL mappings).
- Consider reviewing the source code of [WebMvcAutoConfigurationAdapter][2]
With this in place, static content from myExternalFilePath is served to the /m path, and the default static URL mappings continue to work as well.
Related StackOverflow Q/A: How do I use Spring Boot to serve static content located in Dropbox folder?