繁体   English   中英

依赖于其他属性的 Spring 属性

[英]Spring properties that depend on other properties

我想要一些属性,我可以在 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.Path s。

现在的问题是,出于某种原因,这“在我的机器上工作”(在我的 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;

Spring 表达式可用于引用属性。

在我的例子中是

query-parm=QueryParam1=
query-value=MyParamaterValue

现在在 Spring Bean 中绑定它们。

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

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

暂无
暂无

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

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