
Originally Posted by
jeroenverhagen
Hi all,
I'm experimenting with Spring to find out what it is and what in can do for me. I created a simple definition with 2 singletons of the same object:
<beans>
<bean name="a"
class="com.company.spring.ProjectImpl"
singleton="true">
<constructor-arg>
<value>Hello world a!</value>
</constructor-arg>
</bean>
<bean name="b"
class="com.company.spring.ProjectImpl"
singleton="true">
<constructor-arg>
<value>Hello world b!</value>
</constructor-arg>
</bean>
</beans>
My question is what do I have to do when I do not know beforehand how many of those singletons I need because I need to determine it programmatically?
Maybe it would be better if those beans aren`t singletons. Evertime you retrieve one you get a new instance.
If I need to create beans, I make a Factory:
Code:
class ProjectFactory{
private String _baseName;
private AtomicInteger _counter = new AtomicInteger(0);
public ProjectFactory(String baseName){
_baseName = baseName;
}
public Project create(){
return new ProjectImpl(_baseName+_counter.incAndGet());
}
}
And create the factory in Spring:
Code:
<bean "projectFactory" class="ProjectFactory">
<constructor-arg index="0" value="Hello world"/>
</bean>
And if an objects need a Project, the ProjectFactory could be injected into it:
Code:
class Something{
private ProjectFactory _factory;
Something(ProjectFactory factory){
_factory = factory;
}
void foo(){
Project project = _factory.create();
}
}
And you can write this one in Spring also:
Code:
<bean id="something" class="Something">
<construtor-arg index="0" ref="projectFactory"/>
</bean>