简体   繁体   English

将外部资源文件夹添加到Spring Boot

[英]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: 我想添加一个相对于jar位置的资源文件夹(除了jar中的打包资源),例如:

/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. 使用任一设置访问http://localhost:8080/resources/test.txt会导致出现whitelabel错误页面。 How can I resolve this? 我该如何解决这个问题?

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. 但是只有/Directory启动Spring Boot,因为file:resources/是一个相对路径。

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. 如果您可以将所有内容打包到jar中,那就太好了,但是如果必须引用外部资源,则应该使用绝对路径来避免这样的问题。

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

access file using http://localhost :{port}/files/image.png 使用http:// localhost :{port} /files/image.png访问文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM