Java 如何在spring上下文中注入外部属性文件
我的问题与这个问题完全相同: 这是我之前注入道具文件的方式:Java 如何在spring上下文中注入外部属性文件,java,spring,properties,jar,Java,Spring,Properties,Jar,我的问题与这个问题完全相同: 这是我之前注入道具文件的方式: <util:properties id="smrProps" location="classpath:/spring/SomeProps.properties" /> 但就我的一生而言,当我想要注入一个属性文件时,我不知道在location中使用什么,该文件将与可运行的jar位于同一目录中。我知道类路径指向何处,而我的道具只比它高一级,所以我甚至尝试了classpath:/../SomeProps.proper
<util:properties id="smrProps" location="classpath:/spring/SomeProps.properties" />
但就我的一生而言,当我想要注入一个属性文件时,我不知道在location
中使用什么,该文件将与可运行的jar位于同一目录中。我知道类路径指向何处,而我的道具只比它高一级,所以我甚至尝试了classpath:/../SomeProps.properties
假设它会在父文件夹中查找,但运气不好
例如,如果jar位于:C:\temp\SomeProps.jar
并且属性文件位于C:\temp\SomeProps.properties
如果some.jar在temp中,那么SomeProps.properties也将在temp中。当然,我不能在位置中使用C:\temp\SomeProps.properties
有人能告诉我如何使用这个道具文件吗?我认为使用
util:properties
不可能使用相对路径访问.jar
之外的内容
但是,如果可以,您应该能够通过使用系统属性来实现
另外,您应该使用文件:
而不是类路径:
。大概是这样的:
<util:properties id="smrProps" location="file:{my.path}/SomeProps.properties" />
java -Dmy.path=/YourFolderPath -jar application.jar
另一种解决方案是扩展
属性placeholderconfigure
,然后使用Java
获取.jar
的路径。看看这个问题:另一个解决方案是找出运行jar的路径
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
使用它在父文件夹中查找您的道具文件,并使用SPEL将其注入上下文
下面是它的外观(您可能想稍微整理一下,但我能够模拟您的案例并验证此解决方案):
如果您使用的是弹簧靴,您可以检查
<util:properties id="smrProps" location="'file:' + new java.io.File(T(com.yourpackage.YourClass).getProtectionDomain().getCodeSource().getLocation().getPath()).getParent() + '/'+ settings.prop'" />