gpt4 book ai didi

java - 使用 Spring 环境从类路径注入(inject)文件

转载 作者:行者123 更新时间:2023-12-02 07:06:43 27 4
gpt4 key购买 nike

我的问题:如何使用 Environment 变量在我的类中注入(inject) File

我在属性中指定我需要读取的文件的路径:

myFile.path=classpath:myFile.json

我曾经有一个 XML 应用程序上下文,为该 properties.file 定义一个 property-placeholder,然后我只需使用 @Value 注入(inject)我的文件:

@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(); 但抛出了另一个异常。

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

最佳答案

您可以尝试注入(inject)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();
}
}

关于java - 使用 Spring 环境从类路径注入(inject)文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16010972/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com