弹簧特性取决于其他特性

2022-09-01 03:37:15

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

myDir=/path/to/mydir

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

现在我想通过我的豆子中的@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));
}

正如你所看到的,在我的上下文中,我甚至创建了一个属性编辑器,它可以转换为java.nio.file.Paths。

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

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

答案 1

弹簧可以结合特性

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

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

属性文件

myDir=/path/to/mydir

在课堂上:

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

答案 2

弹簧表达式可用于引用属性。

在我的例子中,它是

query-parm=QueryParam1=
query-value=MyParamaterValue

现在,在春季豆中绑定它们时。

 @Configuration
    public class MyConfig {
    @Value("${query-param}${query-value}")
    private String queryString;
 }

上面的代码会将QueryParam1=MyParamaterValue注入到变量queryString中。


推荐