Currently I have images stored in /src/main/resources/static/myimages in the project directory. Now I want to move these outside of project directory like in /Users/tom/myimages so that in img tag src="/myimages/subdir/first.jpg" in the HTML markup will be loaded from /Users/tom/myimages/subdir/first.jpg. How can I achieve this in spring boot 2.0 project?
This will allow me to add new images without having to recompile the project in production environment.
Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments. You can use properties files, YAML files, environment variables, and command-line arguments to externalize configuration.
Annotation @Document The annotations @Document applied to a class marks this class as a candidate for mapping to the database. The most relevant parameter is value to specify the collection name in the database. The annotation @Document specifies the collection type to DOCUMENT .
You could achieve this, by PathResourceResolver
which is the simplest resolver and its purpose is to find a resource given a public URL pattern. In fact, this is the default resolve.
@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/myimages/**")
.addResourceLocations("/Users/tom/myimages")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new PathResourceResolver());
}
}
PathResourceResolver
in the resource chain as the sole ResourceResolver
in it.PathResourceResolver
, locates the /first.jpg
file in the /Users/tom/myimages
folderMay be you should try to define your own static resource handler ?
It will override the default one.
Something like this:
@Configuration
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("file:/path/to/my/folder/");
}
}
UPDATE That one is something seems to be work on some of my old projects:
@Configuration
@AutoConfigureAfter(DispatcherServletAutoConfiguration.class)
public class CustomWebMvcAutoConfig extends
WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String myExternalFilePath = "file:///C:/Users/tom/imgs/";
registry.addResourceHandler("/imgs/**").addResourceLocations(myExternalFilePath);
super.addResourceHandlers(registry);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With