java - 从 Spring 中的文件路径加载属性文件

标签 java spring filepath

我的应用程序上下文中有以下 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 中传递整个文件位置,这样我就不必添加路径 resource/src/main/properties在创建 InputStream 时?

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

最佳答案

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

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>

最后一个选项可以让您的代码保持干净,并避免您进行加载等操作。

关于java - 从 Spring 中的文件路径加载属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31916525/

相关文章:

java - 为什么我们可以在 java 中创建从 sealed(scala) 派生的新类?

java - Spring 插件未部署在 virgo 上

mysql - 不同的移动计数在 spring 应用程序的 crudRepository 中不起作用

ios - iOS SDK Home 的默认路径未出现在 Titanium Studio 中

java - 更改符号模式/匹配器中的标签

java - setOnClickListener 提示我应该使用 setOnItemClickListener

java - 我的代码无法识别特殊字符

java - 未找到 Redis HashOperations 依赖项?

java - 解析 Eclipse 中的文件路径 - 'File not found' 错误

android - 我们如何知道 Android 应用程序已关闭?