0
votes

Wondering if there is a way to dynamically instantiate beans based on set of values in your property file using PropertyPlaceholderConfigurer class.

I have a java bean say Student with two attributes: "name" and "subject"

I have a property file with:

student.1.name=student1name
student.1.subject=student1subject
student.2.name=student2name
student.2.name=student2subject

Now I have a Classroom object that can take a list of students.

I am wondering if there is a way we could do this using Spring. The challenge here is that the number of students could vary.

If there was only one student object then:

<bean id="student" class="com.abc.Student">
    <property name="name" value="${student.1.name}" />
    <property name="subject"
        value="${student.1.subject}" />
</bean>

<bean id="classRoom" class="com.abc.ClassRoom">
    <property name="student" ref="student" />
</bean>

would have worked. But in this case we have a list of n Students. And the value of n could vary depending on the number of entries in the properties file.

2

2 Answers

0
votes

I'm with Kevin--IMO you're going about this the wrong way.

One possible workaround would be to create a bean that takes the property file as an argument, reads it in, and exposes a list of students (which would need to be indexed on something, like the n in the existing property file).

The classroom bean could then use that list of students.

But it sure looks like you're trying to duplicate the functionality of a DB, without a DB, in an awkward way.

0
votes

I don't think there's a way to do that with PropertyPlaceholderConfigurer. Usually when I have a situation like that I choose a configuration format of either JSON or XML and use GSON/Jackson/JAXB to unmarshall the data into objects.