【问题标题】:Spring console app, load property file from outside of JARSpring 控制台应用程序,从 JAR 外部加载属性文件
【发布时间】:2012-11-01 12:26:57
【问题描述】:

我在控制台 Java 应用程序中使用 Spring。 我的应用程序将部署如下:

folder/myJar.jar
folder/db/connection.properties

如何在应用程序上下文中将 connection.properties 加载到 PropertyPlaceholderConfigurer 中?

我试过了

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="db/connection.properties"/>
</bean>

但它不会起作用。

我的数据库用户名/密码和其他详细信息需要这种方式。

【问题讨论】:

    标签: java spring configuration


    【解决方案1】:

    将前缀file:添加到位置值:

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="file:db/connection.properties"/>
    </bean>
    

    【讨论】:

    • 那不是从文件系统的根目录开始吗?所以它必须存储在/db/connection.properties 或C:/db/connection.properties 中?我认为您想相对于类路径。也许我错过了什么。
    • 相对于项目文件夹@kmb385。 file:/db/properties 分别表示您在 UNIX/Windows 文件系统中所指的内容。
    • 刚刚在 spring 文档中找到它,未附加到 FileSystemApplicationContext(即 FileSystemApplicationContext 不是实际的 ResourceLoader)的 FileSystemResource 将按照您的预期处理绝对路径和相对路径。相对路径是相对于当前工作目录的,而绝对路径是相对于文件系统的根目录的。
    • 是的,这里:static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch05s07.html#resources-filesystemresource-caveats。因此,它总是相对于当前目录,即运行 java 命令的目录。
    【解决方案2】:

    在 value 属性中指定文件在类路径中

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:db/connection.properties"/>
    </bean>
    

    【讨论】:

      猜你喜欢
      • 2014-12-30
      • 2015-08-27
      • 2016-06-18
      • 2015-01-23
      • 1970-01-01
      • 2014-12-16
      • 2012-01-06
      • 1970-01-01
      • 2022-07-26
      相关资源
      最近更新 更多