Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a list from a file .properties using Spring properties place holder

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

Context file

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

Properties File

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

Any help would be much appreciated

like image 412
Lici Avatar asked Oct 21 '09 06:10

Lici


2 Answers

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>

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>

In your 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
}

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

like image 130
ChssPly76 Avatar answered Oct 05 '22 20:10

ChssPly76


A simpler solution:

class Z {
    private List<String> urlList;
    // add setters and getters
}

your bean definition

<bean name="XXX" class="XX.YY.Z">
      <property name="urlList" value="#{'${prop.list}'.split(',')}"/>
</bean>

Then in your property file:

prop.list=a,b,c,d
like image 31
Paul Pacheco Avatar answered Oct 05 '22 19:10

Paul Pacheco