使用Spring属性占位符从文件.properties读取列表 [英] Reading a list from a file .properties using Spring properties place holder

查看:356
本文介绍了使用Spring属性占位符从文件.properties读取列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Spring属性占位符填充bean列表属性.

I want to fill a bean list property using Spring properties place holder.

<bean name="XXX" class="XX.YY.Z">
      <property name="urlList">
            <value>${prop.list}</value>
      </property>
</bean>

属性文件

prop.list.one=foo
prop.list.two=bar

任何帮助将不胜感激

推荐答案

使用

Use a util:properties element to load your properties. You can use PropertyPlaceholderConfigurer to specify the path to your file:

<bean name="XXX" class="XX.YY.Z">
  <property name="urlList">
    <util:properties location="${path.to.properties.file}"/>
  </property>
</bean>

更新我误解了这个问题;您只想返回键以特定字符串开头的属性.最简单的方法是在bean的setter方法中实现.您必须将字符串作为单独的属性传递给bean.扩展以上声明:

Update I've misunderstood the question; you only want to return properties where key starts with specific string. The easiest way to achieve that would be to do so within setter method of your bean. You'll have to pass the string to your bean as a separate property. Extending the above declaration:

<bean name="XXX" class="XX.YY.Z" init-method="init">
  <property name="propertiesHolder">
     <!-- not sure if location has to be customizable here; set it directly if needed -->
    <util:properties location="${path.to.properties.file}"/>
  </property>
  <property name="propertyFilter" value="${property.filter}" />
</bean>

在您的XX.YY.Z bean中:

private String propertyFilter;
private Properties propertiesHolder;
private List<String> urlList;

// add setter methods for propertyFilter / propertiesHolder

// initialization callback
public void init() {
  urlList = new ArrayList<String>();
  for (Enumeration en = this.propertiesHolder.keys(); en.hasMoreElements(); ) {
    String key = (String) en.nextElement();
    if (key.startsWith(this.propertyFilter + ".") { // or whatever condition you want to check
      this.urlList.add(this.propertiesHolder.getProperty(key));
    }
  } // for
}

如果需要在许多不同的地方执行此操作,则可以将以上功能包装到FactoryBean中.

If you need to do this in many different places you can wrap the above functionality into a FactoryBean.

这篇关于使用Spring属性占位符从文件.properties读取列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆