【问题标题】:How to Inject an external properties file in spring context如何在 Spring 上下文中注入外部属性文件
【发布时间】:2013-07-01 17:38:35
【问题描述】:

我的问题与此问题完全相同: Spring application context external properties?

这就是我之前注入 props 文件的方式:

<util:properties id="smrProps" location="classpath:/spring/SomeProps.properties" />  

但是对于我的生活,当我想注入一个与可运行 jar 位于同一目录中的属性文件时,我无法弄清楚在 location 中使用什么。我知道类路径指向的位置,并且我的道具只是上一级,所以我什至尝试了classpath:/../SomeProps.properties,假设它会在父文件夹中查找,但没有运气。

例如,如果 jar 位于:C:\temp\some.jarand 属性文件位于 C:\temp\SomeProps.properties

如果 some.jar 在 temp 中,那么 SomeProps.properties 也将在 temp 中。当然,我不能在 location 中使用 C:\temp\SomeProps.properties

有人可以指导我如何使用这个道具文件吗?

【问题讨论】:

标签: java spring properties jar


【解决方案1】:

我认为不可能使用相对路径通过util:properties 访问.jar 之外的内容。

但是,如果可以的话,你应该可以通过使用系统属性来做到这一点。

另外,您应该使用file: 而不是classpath:。像这样:

<util:properties id="smrProps" location="file:{my.path}/SomeProps.properties" />

然后用类似这样的方式执行 .jar:

java -Dmy.path=/YourFolderPath -jar application.jar

另一种解决方案是扩展PropertyPlaceholderConfigurer,然后使用Java 获取.jar 的路径。看看这个问题:Loading Properties with Spring (via System Properties)

【讨论】:

    【解决方案2】:

    另一种解决方案是找出运行jar的路径

    return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
    

    使用它在父文件夹中找到你的 prop 文件并使用 SPEL 将其注入到上下文中

    这是它的外观(你可能想稍微整理一下,但我能够模拟你的情况并验证了这个解决方案):

    <util:properties id="smrProps" location="'file:' + new java.io.File(T(com.yourpackage.YourClass).getProtectionDomain().getCodeSource().getLocation().getPath()).getParent() + '/'+ settings.prop'" />
    

    【讨论】:

      猜你喜欢
      • 2019-07-31
      • 2012-01-06
      • 1970-01-01
      • 2020-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-01
      • 2018-02-21
      相关资源
      最近更新 更多