【发布时间】:2016-07-08 07:21:05
【问题描述】:
我想要一些属性,我可以通过 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}"
【问题讨论】:
-
您可能可以将
${myDir}放在属性文件中(恕我直言,值得一试) -
或者使用
myFile=myfile.txt然后使用@Value("${myDir}/${myFile}")