【问题标题】:Spring properties that depend on other properties依赖于其他属性的弹簧属性
【发布时间】: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}")

标签: java spring


【解决方案1】:

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

在我的例子中是

query-parm=QueryParam1=
query-value=MyParamaterValue

现在在 Spring Bean 中绑定它们。

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

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

【讨论】:

    【解决方案2】:

    Spring可以组合属性

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

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

    属性文件

    myDir=/path/to/mydir
    

    在课堂上:

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

    【讨论】:

    • 谢谢西尔维安!我已经有了这个解决方案,但是我错过了在文件中定义组合的想法。
    • 你知道如果myDir 和myFile 在application.properties 中定义,并且你在application-dev.properties 中为特定的Spring 配置文件覆盖myDir 会发生什么吗? myFile 会被重新计算吗?
    • 如果myFile 在application.properties 中定义,但没有${myDir},则没有。如果您包含它,例如:myFile = ${myDir}/mySubfolder/myfile.txt,那么在这种情况下,是的,当您使用 de dev profile 时,它​​会重新计算它
    猜你喜欢
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 2011-09-09
    • 2011-08-20
    • 2018-03-26
    • 1970-01-01
    • 2021-06-22
    • 2017-02-08
    相关资源
    最近更新 更多