Reputation: 284
I have a spring web application. Let's say it is managing an animals zoo. In my property file I am writing how much animals there are and for each animal its type and name as following :
animal.number = 2
animal.1.type= tall
animal.1.name= Simba
animal.2.type= small
animal.2.name= Pumba
Now i would like to use this property in my application using spring way. In my config.xml i could write something like following.
<bean id="animal" class="com.zoo.animalsManaging">
<property name="animalNumber" value="${animal.number}" />
<property name="animal1Name" value="${animal.1.name}" />
<property name="animal1Type" value="${ animal.1.type}" />
<property name="animal2Name" value="${animal.2.name}" />
<property name="animal2Type" value="${ animal.2.type}" />
</bean>
The problem is that animalNumber will always change. I am wondering if there is a spring way to get the entire animal property and then access to sub property by let's say animal.1.type.
Upvotes: 1
Views: 82
Reputation: 3364
As guided here you can use the util:properties
Animal properties
animal.1.type= tall
animal.1.name= Simba
animal.2.type= small
animal.2.name= Pumba
animal.number= 2
application.xml configuration
<context:property-placeholder location="classpath:animal.properties"/>
<bean name="zoo" class="com.stack.Zoo" init-method="init">
<property name="animalProperties">
<!-- not sure if location has to be customizable here; set it directly if needed -->
<util:properties location="${classpath:animal.properties}"/>
</property>
<property name="numberOfAnimals" value="${animal.number}" />
</bean>
Zoo is class Hold list of animals from Properties.
public class Zoo {
Properties animalProperties;
private Integer numberOfAnimals;
List<Animal> animals;
public void init() {
animals = new ArrayList<Animal>();
if (numberOfAnimals > 0) {
StringBuffer key = new StringBuffer();
for (int i = 1; i <= numberOfAnimals; i++) {
key.setLength(0);
key.append("animal.").append(i).append(".type");
String type = this.animalProperties.getProperty(key.toString());
key.setLength(0);
key.append("animal.").append(i).append(".name");
String name = this.animalProperties.getProperty(key.toString());
animals.add(new Animal(name,type));
System.out.println("Animals Added");
}
}
}
// Setter and getter Methods
}
In Post Construct , we are reading the properties and creating the Animal Instances.
numberOfAnimals value injected by Spring.
Upvotes: 2