繁体   English   中英

使用Spring Environment从类路径中注入文件

[英]Inject File from classpath using Spring Environment

我的问题:如何使用Environment变量在我的类中注入一个File

我在properties指定了我需要读取的文件的路径:

myFile.path=classpath:myFile.json

我曾经有一个XML应用程序上下文定义了properties.fileproperty-placeholder ,然后我可以使用@Value注入我的文件:

@Value("${myFile.path}")
private File myFile;

然而,现在我想做一些事情:

@Inject
private Environment environment;

private File myFile;

@PostConstruct
private void init() {
    myFile = environment.getProperty("myFile.path", File.class);
}

但抛出异常:

Caused by: java.io.FileNotFoundException: 
    classpath:myFile.json (No such file or directory)

我也试过像myFile = environment.getProperty("myFile.path", Resource.class).getFile(); 但抛出了另一个例外。

知道属性中定义的路径可以是绝对路径还是类路径相对,我如何实现注入文件?

您可以尝试注入ResourceLoader ,并使用它来加载引用的类路径资源:

@Autowired
private ResourceLoader resourceLoader;

...

@PostConstruct
private void init() {
    String resourceReference = environment.getProperty("myFile.path");
    Resource resource = resourceLoader.getResource(resourceReference);
    if (resource != null) {
        myFile = resource.getFile();
    }
}

暂无
暂无

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

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