【问题标题】:Spring boot - load file from outside classpathSpring boot - 从外部类路径加载文件
【发布时间】:2018-12-19 19:34:34
【问题描述】:

我必须从我的类路径之外加载文件。 位置取决于环境属性:

  • 在开发属性中我想从资源文件夹加载文件
  • 在产品属性中,我想从路径 (/location/file) 加载文件

最好的方法是什么?

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    一个可能的解决方案是使用配置属性和Resource。例如,像这样定义您的属性:

    @ConfigurationProperties(prefix = "app")
    public class SomeProperties {
        private Resource file;
    
        // Getters + Setters
    }
    

    然后通过在任何类上使用 @EnableConfigurationProperties 注释来启用您的配置属性,例如您的主类:

    @SpringBootApplication
    @EnableConfigurationProperties(SomeProperties.class)
    public class Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    

    要配置文件位置,可以在开发中使用如下:

    app.file=classpath:test.txt
    

    在生产环境中你可以使用:

    app.file=file:/usr/local/test.txt
    

    现在您可以在任何其他服务中自动装配SomeProperties 类。 Resource 类有一个 getFile() 方法,允许您检索文件,但除此之外,它还包含其他几个有用的方法。

    【讨论】:

    • 我有这样的工作。但是,如果 File/Resource 尚不存在,我该如何创建它? (例如第一次运行时创建文件)
    • @JackStraw 如果它不存在,我认为 spring 不会抛出异常,因此您可以使用在this question 中找到的众多答案之一来创建文件(如果它不存在) .
    猜你喜欢
    • 2015-06-11
    • 1970-01-01
    • 2019-03-04
    • 2020-06-05
    • 1970-01-01
    • 2020-11-09
    • 2014-12-16
    • 1970-01-01
    • 2017-09-07
    相关资源
    最近更新 更多