Creating list of beans based on property file in spring

properties, spring

Solution

So I decided to prove I'm not that lazy. The solution has some obvious limitations like 1 level of properties or being able t oset primitives types only. But meets my needs. So for record:

Property file:

student.1.firstName=Jan
student.1.lastName=Zyka
student.1.age=30
student.2.firstName=David
student.2.lastName=Kalita
student.2.age=55

Student class:

package com.jan.zyka.test.dao;

public class Student {

    private String firstName;
    private String lastName;
    private int age;
    private String common;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCommon() {
        return common;
    }

    public void setCommon(String common) {
        this.common = common;
    }

    @Override
    public String toString() {
        return "Student{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", age=" + age +
                ", common='" + common + '\'' +
                '}';
    }
}

Spring definition:

<bean id="studentFactory" class="com.jan.zyka.test.BeanListFactory">
    <property name="propertyPrefix" value="student" />
    <property name="commonProperties">
        <map>
            <entry key="common" value="testCommonValue" />
        </map>
    </property>
    <property name="targetType">
        <value type="java.lang.Class">com.jan.zyka.test.dao.Student</value>
    </property>
    <property name="properties">
        <util:properties location="classpath:testListFactory.properties" />
    </property>
</bean>

Results in:

[
 Student{firstName='Jan', lastName='Zyka', age=30, common='testCommonValue'},  
 Student{firstName='David', lastName='Kalita', age=55, common='testCommonValue'}
]

Factory bean itself:

package com.jan.zyka.test;

import com.google.common.primitives.Primitives;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.FactoryBean;

import java.beans.PropertyDescriptor;
import java.util.*;

/**
 * <p>
 *    Creates list of beans based on property file.
 * </p>
 * <p>
 *    Each object should be defined in the property file as follows:
 *    <pre>
 *        &lt;prefix&gt;.&lt;index&gt;.&lt;property&gt;
 *    </pre>
 *
 *    So one example might be:
 *    <pre>
 *        student.1.firstName=Paul
 *        student.1.lastName=Verlaine
 *        student.2.firstName=Alex
 *        student.2.lastName=Hamburger
 *    </pre>
 *
 *    The target class must provide default constructor and setter for each property defined in the configuration file as per
 *    bean specification.
 * </p>
 *
 * @param <T> type of the target object
 */
public class BeanListFactory<T> implements FactoryBean<List<T>> {

    private String propertyPrefix;
    private Map<String, Object> commonProperties = Collections.emptyMap();
    private Class<T> targetType;
    private Properties properties;

    private List<T> loadedBeans;

    public String getPropertyPrefix() {
        return propertyPrefix;
    }

    public void setPropertyPrefix(String propertyPrefix) {
        this.propertyPrefix = propertyPrefix;
    }

    public Map<String, Object> getCommonProperties() {
        return commonProperties;
    }

    public void setCommonProperties(Map<String, Object> commonProperties) {
        this.commonProperties = commonProperties;
    }

    public Class<T> getTargetType() {
        return targetType;
    }

    public void setTargetType(Class<T> targetType) {
        this.targetType = targetType;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    @Override
    public List<T> getObject() throws Exception {

        loadedBeans = new ArrayList<T>();
        int lastIndex = -1;

        T item = null;

        for (String property: prefixFilteredProperties()) {

            // The actual value
            final String propertyValue = properties.getProperty(property);

            // Remove Prefix
            property = property.substring(propertyPrefix.length() + 1);

            // Split by "."
            String tokens[] = property.split("\\.");

            if (tokens.length != 2) {
                throw new IllegalArgumentException("Each list property must be in form of: <prefix>.<index>.<property name>");
            }

            final int index = Integer.valueOf(tokens[0]);
            final String propertyName = tokens[1];

            // New index
            if (lastIndex != index) {
                if (lastIndex !=-1) {
                    loadedBeans.add(item);
                }
                lastIndex = index;

                item = targetType.newInstance();
                setCommonProperties(item, commonProperties);
            }

            // Set the property
            setProperty(item, propertyName, convertIfNecessary(propertyName, propertyValue));
        }

        // Add last item
        if (lastIndex != -1) {
            loadedBeans.add(item);
        }

        return loadedBeans;
    }

    @Override
    public Class<?> getObjectType() {
        return ArrayList.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }

    private Object convertIfNecessary(String propertyName, String propertyValue) throws Exception {
        PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(targetType, propertyName);
        Class<?> propertyType = Primitives.wrap(descriptor.getPropertyType());

        if (propertyType == String.class) {
            return propertyValue;
        }

        return propertyType.getDeclaredMethod("valueOf", String.class).invoke(propertyType, propertyValue);
    }

    private Set<String> prefixFilteredProperties() {
        Set<String> filteredProperties = new TreeSet<String>();

        for (String propertyName: properties.stringPropertyNames()) {
            if (propertyName.startsWith(this.propertyPrefix)) {
                filteredProperties.add(propertyName);
            }
        }

        return filteredProperties;
    }

    private void setCommonProperties(T item, Map<String, Object> commonProperties) throws Exception {
        for (Map.Entry<String, Object> commonProperty: commonProperties.entrySet()) {
            setProperty(item, commonProperty.getKey(), commonProperty.getValue());
        }
    }

    private static void setProperty(Object item, String propertyName, Object value) throws Exception {
        PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(item.getClass(), propertyName);
        descriptor.getWriteMethod().invoke(item, value);
    }
}

Problem

I would like to create list of beans based on property files in spring. To illustrate the problem lets say I have a `ClassRoom`. ``` public class ClassRoom { private List<Student> students; public void setStudents(List<Student> students) { this.students = students; } } public class Student { private Strign firstName; private String lastName; /* cosntructor, setters, getters ... */ } ``` So normally I will do in my .xml spring config: ... ``` <property name="student"> <list> <bean id="student1" class="Student" ...> <property name="firstName" value="${student.name}" /> <property name="lastName" value="${student.surname}" /> </bean> ... </list> <property> ``` But now I have several property files - one per each environment, the corrent one is included based on system property which defines the environment - and the number of students is different in each environment. So what I'm looking for is having property file like: ``` student.1.fistName=Paul student.1.lastName=Verlaine student.2.firstName=Alex student.2.lastName=Hamburger ``` And some nice utility which converts such file into `List` of my `Student` classes. Sofar I went with having separate .xml configuration file for the list of students which is being included into my spring configuration but I don't particularly like the idea of providing part of the xml configuration to the client. I believe this should be separated. So the question: is there any cool spring utility which can do this for me? Or is it up to me to write one?

Original source