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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32339172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 20:03:02  来源:igfitidea点击:

Add external resources folder to Spring Boot

javaspringspring-mvcspring-boot

提问by cscan

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.txtwith either setup leads to a whitelabel error page. How can I resolve this?

http://localhost:8080/resources/test.txt使用任一设置访问都会导致白标签错误页面。我该如何解决这个问题?

回答by approxiblue

Your second approach would work:

你的第二种方法会起作用:

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

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

当您从 启动 Spring Boot 时/Directory,因为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 pathsto avoid problems like this.

如果你能把所有的东西都打包到 jar 中就好了,但是如果你必须引用外部资源,你应该使用绝对路径来避免这样的问题。

回答by Nowshad Hossain

 @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访问文件