gpt4 book ai didi

java - 依赖于其他属性的 Spring 属性

转载 作者:IT老高 更新时间:2023-10-28 13:52:39 27 4
gpt4 key购买 nike

我想要一些属性,我可以通过 spring bean 中的 @Value 引用,这些属性只能依赖于其他属性来创建。特别是我有一个属性,它描述了目录的文件系统位置。

myDir=/path/to/mydir

按照惯例,该目录中有一个文件,始终称为 myfile.txt

现在我想通过我的 bean 中的 @Value 注释来访问目录和文件。有时我想以字符串的形式访问它们,有时以 java.io.Files 的形式访问它们,有时以 org.springframework.core.io.FileSystemResource 的形式访问它们(顺便说一下,它开箱即用!)。但是因为不能按需连接字符串。

所以我当然可以做的只是声明两者,但我最终会得到

myDir=/path/to/mydir
myFile/path/to/mydir/myfile.txt

我想避免这种情况。

所以我想出了一个 @Configuration 类,它接受属性并将其添加为新的 PropertySource:

@Autowired
private ConfigurableEnvironment environment;

@Value("${myDir}")
private void addCompleteFilenameAsProperty(Path myDir) {
Path absoluteFilePath = myDir.resolve("myfile.txt");

Map<String, Object> props = new HashMap<>();
props.put("myFile, absoluteFilePath.toString());
environment.getPropertySources().addFirst(new MapPropertySource("additional", props));
}

如您所见,在我的上下文中,我什至创建了一个 PropertyEditor,它可以转换为 java.nio.file.Paths。

现在的问题是,由于某种原因,这“在我的机器上工作”(在我的 IDE 中),但不能在预期的目标环境中运行。我明白了

java.lang.IllegalArgumentException: Could not resolve placeholder 'myFile' in string value "${myFile}"

最佳答案

Spring可以组合属性

myDir=/path/to/mydir 
myFile=${myDir}/myfile.txt

您也可以使用默认值而不首先在属性中定义 myFile:

属性文件

myDir=/path/to/mydir

在类里面:

@Value("#{myFile:${myDir}/myfile.txt}")
private String myFileName;

关于java - 依赖于其他属性的 Spring 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36136874/

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