【问题标题】:Loading a properties file from a file path in Spring在 Spring 中从文件路径加载属性文件
【发布时间】:2015-08-10 09:54:23
【问题描述】:

我的应用程序上下文中有以下 bean:

<bean id="httpClient" factory-method="createHttpClient" class="com.http.httpclient.HttpClientFactory">
    <constructor-arg>
        <bean id="httpConfig" class="com.http.httpclient.HttpClientParamsConfigurationImpl">
            <constructor-arg value="httpclient.properties"/>
        </bean>
    </constructor-arg>
</bean>

httpclient.properties 是我的属性文件的名称。我在HttpClientParamsConfigurationImpl 中使用这个参数来读取文件(不要太在意错误处理):

public HttpClientParamsConfigurationImpl(String fileName) {
  try(InputStream inputStream = new FileInputStream("resource/src/main/properties/" + fileName)) {
     properties.load(inputStream);
  } catch (IOException e) {
     LOG.error("Could not find properties file");
     e.printStackTrace();
  }
}

有没有办法在 bean 中传递整个文件位置,这样我就不必在创建 InputStream 时添加路径 resource/src/main/properties

我尝试过classpath:httpclient.properties,但它不起作用。

【问题讨论】:

  • resource/src/main/properties/ 在你的类路径中吗?无论如何,为什么不将resource/src/main/properties/httpclient.properties 传递为constructor-arg
  • 我想避免传递整个位置以防万一它发生变化。我只是想给出文件名。是的,该文件夹在我的类路径中。
  • stackoverflow.com/a/7246629/1898397 这个答案在这里看起来很相关。

标签: java spring filepath


【解决方案1】:

您的代码错误,文件位于类路径中(src/main/resources 已添加到类路径中,并且其中的文件被复制到类路径的根目录中。在您的情况下,位于名为 properties 的子目录中)。而不是String,我建议您使用ResourceProperties

public HttpClientParamsConfigurationImpl(Resource res) {
  try(InputStream inputStream = res.getInputStream()) { 
      properties.load(inputStream);
  } catch (IOException e) {
   LOG.error("Could not find properties file");
   e.printStackTrace();
  }
}

然后在您的配置中,您可以简单地编写以下内容:

<bean id="httpClient" factory-method="createHttpClient" class="com.http.httpclient.HttpClientFactory">
    <constructor-arg>
        <bean id="httpConfig" class="com.http.httpclient.HttpClientParamsConfigurationImpl">
            <constructor-arg value="classpath:properties/httpclient.properties"/>
        </bean>
    </constructor-arg>
</bean>

或者更好的是,甚至不用加载属性,只需将它们传递给构造函数,让 Spring 为您完成所有的硬加载。

public HttpClientParamsConfigurationImpl(final Properties properties) {
    this.properties=properties
}

然后使用util:properties 加载属性并简单地为构造函数引用它。

<util:properties id="httpProps" location="classpath:properties/httpclient.properties" />

<bean id="httpClient" factory-method="createHttpClient" class="com.http.httpclient.HttpClientFactory">
    <constructor-arg>
        <bean id="httpConfig" class="com.http.httpclient.HttpClientParamsConfigurationImpl">
            <constructor-arg ref="httpProps"/>
        </bean>
    </constructor-arg>
</bean>

最后一个选项可以让你的代码保持干净,让你免于加载等操作。

【讨论】:

    猜你喜欢
    • 2015-01-23
    • 2020-06-05
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    相关资源
    最近更新 更多