Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add external resources folder to Spring Boot

I'd like to add a resource folder relative to the location of the jar (in addition to packaged resources within my jar), for example:

/Directory
    Application.jar
    /resources
        test.txt

I've tried the following:

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

I've also tried:

.addResourceLocations("/resources/", "file:resources/");

Accessing http://localhost:8080/resources/test.txt with either setup leads to a whitelabel error page. How can I resolve this?

like image 414
cscan Avatar asked Sep 01 '15 19:09

cscan


People also ask

How do I add a resource folder to a jar file?

1) click project -> properties -> Build Path -> Source -> Add Folder and select resources folder. 2) create your JAR!

How do I configure externalize in Spring boot?

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.


2 Answers

Your second approach would work:

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

but only if you launched Spring Boot from /Directory, because file:resources/ is a relative path.

cd Directory
java -jar Application.jar

It's nice if you can pack everything into the jar, but if you have to reference external resources, you should use absolute paths to avoid problems like this.

like image 171
approxiblue Avatar answered Oct 16 '22 17:10

approxiblue


 @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry
            .addResourceHandler("/files/**")
            .addResourceLocations("file:/location1/", "file:/location2/");
}

access file using http://localhost:{port}/files/image.png

like image 1
Nowshad Hossain Avatar answered Oct 16 '22 16:10

Nowshad Hossain