Spring PropertySource中的三元运算符似乎不起作用

时间:2016-11-08 17:46:57

标签: java spring configuration configuration-files ternary-operator

我正在使用Spring Framework 4.2.5,并且正在运行可执行的JAR。我想要做的是在配置类上配置一个@PropertySource:

  1. 从磁盘上的文件加载属性,该文件的路径由命令行上的系统属性“config.file”指定(如果存在该系统属性)。
  2. 如果未设置'config.file'属性,则从类路径上的默认属性文件加载属性。
  3. 如果我能够在这种情况下使用Spring Boot,这不会是一个问题。我几乎可以到达那里:

    @PropertySource({"classpath:default.properties", "${config.file}"})
    

    除了这样做之外(据我所知) config.file 需要指定为'file:path / to / file'而不仅仅是'path / to / file ',如果可能,我想避免。所以我转向SPEL三元运算符,提出了以下内容:

    @PropertySource("#{'${config.file}' != '' ? 'file:${config.file}' : 'classpath:default.properties'}")
    

    (以及主题的一些其他变体),但我最终得到的是属性源尝试从以下一个加载,具体取决于config.file的存在:

    '' != '' ? 'file:' : 'classpath:default.properties'
    'my.props' != '' ? 'file:my.props' : 'classpath:default.properties'
    

    这是扩展但未评估的字符串。我不确定我是在正确地执行SPEL还是三元运算符(我的赌注在这里),或者@PropertySource不会完全评估SPEL。任何见解或建议将不胜感激。

    更新

    我也尝试过使用多个@PropertySource注释:

    @PropertySource("classpath:default.properties")
    @PropertySource(value="${config.file}", ignoreResourceNotFound=true)
    

    这似乎是一种应该工作的方法,而Spring确实尝试处理第二个@PropertySource,但无论使用“file:path / to / file”,“file:// path / to /”指定的是什么文件“或简单地”路径/到/文件“,我被告知”类路径资源[值]无法打开,因为它不存在“。通过文档中给出的示例,似乎允许非类路径资源,但这不是我所看到的行为。

0 个答案:

没有答案
相关问题