使用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.