Spring Boot-从外部类路径加载文件

时间:2018-07-11 17:07:13

标签: java spring spring-boot

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

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

最好的方法是什么?

1 个答案:

答案 0 :(得分: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()方法,该方法允许您检索文件,但除此之外,它还包含其他几种有用的方法。

相关问题