当前位置: 移动技术网 > IT编程>开发语言>Java > Spring用代码来读取properties文件实例解析

Spring用代码来读取properties文件实例解析

2019年07月19日  | 移动技术网IT编程  | 我要评论

有些时候,我们需要以spring代码直接读取properties配置文件,那么我们要如何操作呢?下面我们来看看具体内容。

我们都知道,spring可以@value的方式读取properties中的值,只需要在配置文件中配置

org.springframework.beans.factory.config.propertyplaceholderconfigurer

<bean id="propertyconfigurer" class="org.springframework.beans.factory.config.propertyplaceholderconfigurer">
    <property name="location">
      <value>classpath:config.properties</value>
    </property>
  </bean>

那么在需要用到这些获取properties中值的时候,可以这样使用

  @value("${sql.name}")
  private string sqlname;

但是这有一个问题,我每用一次配置文件中的值,就要声明一个局部变量。有没有用代码的方式,直接读取配置文件中的值。

答案就是重写propertyplaceholderconfigurer

public class propertyplaceholder extends propertyplaceholderconfigurer {

  private static map<string,string> propertymap;

  @override
  protected void processproperties(configurablelistablebeanfactory beanfactorytoprocess, properties props) throws beansexception {
    super.processproperties(beanfactorytoprocess, props);
    propertymap = new hashmap<string, string>();
    for (object key : props.keyset()) {
      string keystr = key.tostring();
      string value = props.getproperty(keystr);
      propertymap.put(keystr, value);
    }
  }

  //static method for accessing context properties
  public static object getproperty(string name) {
    return propertymap.get(name);
  }
}

在配置文件中,用上面的类,代替propertyplaceholderconfigurer

 <bean id="propertyconfigurer" class="com.gyoung.mybatis.util.propertyplaceholder">
    <property name="location">
      <value>classpath:config.properties</value>
    </property>
  </bean>

这样在代码中就可以直接用编程方式获取

 propertyplaceholder.getproperty("sql.name");

如果是多个配置文件,配置locations属性

<bean id="propertyconfigurer"
     class="com.gyoung.mybatis.util.propertyplaceholder">
    <property name="ignoreresourcenotfound" value="true"/>
    <property name="locations">
      <list>
        <value>file:./jdbc.properties</value>
        <value>file:./module.config.properties</value>
        <value>classpath:jdbc.properties</value>
        <value>classpath*:*.config.properties</value>
      </list>
    </property>
  </bean>

总结

以上就是本文关于spring用代码来读取properties文件实例解析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:

spring实例化bean过程解析及完整代码示例

spring工厂方法创建(实例化)bean实例代码

如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网