Reputation: 641
I have an object namely, Counter
public class Counter{
private String counterGroup;
private String counterName;
private String counterValue;
//getters & setters
}
public class Task{
private String taskName;
private List<Counter> counters;
//getters & setters
}
In my spring.xml
<context:property-placeholder location="classpath:/test.properties"/>
<bean id="task" class="com.test.Task">
<property name="taskName" value="${task.name}"/>
<property name="counters">
<list>
<ref bean="counter1"/>
<ref bean="counter2"/>
</list>
</bean>
<bean id="counter1" class="com.test.Counter">
<property name="counterGroup" value=${counter.group1}/>
<property name="counterName" value=${counter.name1}/>
<property name="counterValue" value=${counter.value1}/>
</bean>
<bean id="counter2" class="com.test.Counter">
<property name="counterGroup" value=${counter.group2}/>
<property name="counterName" value=${counter.name2}/>
<property name="counterValue" value=${counter.value2}/>
</bean>
In the test.properties
task.name=task1
counter.group1=g1
counter.name1=n1
counter.value1=v1
counter.group2=g2
counter.name2=n2
counter.value2=v2
If I have more number of counters then I have to edit both the properties as well as the spring.xml file. As I'm new to Spring and Java, I don't believe this is the right approach to solve this issue.
Can anybody suggest a different approach to solve the same issue.
Upvotes: 1
Views: 841
Reputation: 202
Well, that is probably approach to use. However you may make your application looks better, if you use factory methods and object builders. For example:
public class Counter {
.......
public static Counter createFor(String descriptor){
String[] params = descriptor.split(":");
return new Counter(params[0], params[1], params[2]);
}
}
your context:
<bean id="task" class="com.test.Task">
<property name="taskName" value="${task.name}"/>
<property name="counters">
<list>
<bean class="com.test.Counter" factoryMethod="createFor">
<constructor-arg ref="${counter.descriptor1}"/>
</bean>
<bean class="com.test.Counter" factoryMethod="createFor">
<constructor-arg ref="${counter.descriptor2}"/>
</bean>
</list>
</bean>
In the test.properties
task.name=task1
counter.descriptor1=g1:n1:v1
counter.descriptor2=g2:n2:v2
Of course you're not limited by this and may upgrade or apply any similar design techniques.
Upvotes: 1