【问题标题】:Spring PropertyPlaceHolder Java Config external properties fileSpring PropertyPlaceHolder Java Config 外部属性文件
【发布时间】:2015-01-03 02:52:16
【问题描述】:

所以这一定是一个愚蠢的错误,我无法通过。我正在尝试将我的属性文件外部化,该文件当前放置在我的用户主页中。我正在使用@PropertySource 加载属性文件,如下所示:

@Configuration
@PropertySources(value = { @PropertySource("file:#{systemProperties['user.home']}/.invoice/config.properties") })
public class PropertiesConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertiesPlaceHolderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

但不幸的是,这并没有加载属性文件。抛出FileNotFoundException。但是,如果我将路径更改为:

@PropertySources(value = { @PropertySource("file:/home/rohit/.invoice/config.properties") })

它工作正常。这就是先前路径解析的路径。我已经记录下来验证。所以在我看来,SpEL 没有在 @PropertySource 注释中得到评估。它应该这样工作吗?

如果是,那么还有其他方法可以读取位于/home/rohit 中的外部属性文件吗?出于显而易见的原因,我不想给出绝对路径。而且我想避免扩展PropertyPlaceHolderConfigurer 类。

我尝试的另一个选项是将 /home/rohit/.invoice 文件夹添加到 tomcat 类路径。但似乎 Spring 不使用 System Classpath 来解析 classpath: 后缀。有没有这方面的指点?

【问题讨论】:

  • 表达式不起作用,请改用file:${user.home}/.invoice/config.properties
  • @M.Deinum 让我试试..
  • @M.Deinum Ahaa!!它起作用了:)将其作为答案发布,所以我可以接受:)

标签: java spring properties classpath spring-el


【解决方案1】:

@PropertySoure 注释中,EL 表达式将不起作用。您可以使用占位符${...},但这也仅限于系统或环境变量。但是,当您要解析用户的主目录时,您可以使用 ${user.home} 占位符。

@PropertySource("file:${user.home}/.invoice/config.properties")

这应该可以正常工作。

【讨论】:

    猜你喜欢
    • 2020-07-30
    • 2012-08-01
    • 2018-02-21
    • 2015-06-26
    • 2015-05-14
    • 1970-01-01
    • 2011-12-10
    • 2017-08-18
    相关资源
    最近更新 更多