Issue
Say I have this properties file:
students.bill.firstname=John
students.bill.lastname=Doe
students.bill.age=20
students.jim.firstname=Jim
students.jim.lastname=Wright
students.jim.age=21
.
.
.
I want an xml bean that contains a map of students that has their firstname as the key.
Object example:
Student.java
public class Student {
String firstname;
String lastname;
Integer age;
}
Classroom.java
public class Classroom {
Map<String, Student> students;
}
What I am looking for is a way to maybe say, create a student bean from properties students.bill.* and add it to the classroom bean map. Then make one for students.jim.* and add it to the classroom bean map. I am really not wanting to create a bean for each student and go through and put each and every value in them.
Solution
Spring already supports that out of the box, since Spring 0.9 (but not many people know about that).
You would need to modify your property file slightly.
student.(class)=your.package.here.Student
student.(abstract)=true
jim.(parent)=student
jim.firstname=Jim
jim.lastname=Wright
jim.age=21
... Other student based definitions here.
Now you can use a BeanFactory
together with a PropertiesBeanDefinitionReader
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(bf);
reader.loadBeanDefinitions(new ClassPathResource("students.properties"));
Map<String, Student> students = bf.getBeansOfType(Student.class);
Now if you have a new student just add it to the properties file and reload.
Answered By - M. Deinum