A common pattern I am falling into with my beans is as follows:
public class PrototypeBean {
private SingletonBean singletonBean;
private int value;
public PrototypeBean(int value, singletonBean) {
this.value = value;
this.singletonBean = singletonBean;
}
}
I cannot for the life of me figure out what is the cleanest way to instantiate a prototype bean like this if I do not know what value will be until runtime. My current pattern is as follows:
public class FactoryImpl implements Factory{
private SingletonBean singletonBean;
public FactoryImpl(SingletonBean singletonBean) {
this.singletonBean = singletonBean;
}
public PrototypeBean getPrototypeBean(int value) {
return new PrototypeBean(value, singletonBean);
}
}
Where Factoryimpl is wired together in XML. This still seems horrible to me and feels like I am breaking IoC. Is there a cleaner way of doing this in spring?
This is one of the most wanted features missing in Spring I came across. Basically your solution is the best workaround I can think of (just make
singletonBeanandvaluefieldsfinal).Another approach would be to let Spring create
PrototypeBeanwith only one constructor argument (SingletonBean) and passingvalueafterwards (see: Best way to refactor this in Spring?). However this is less clean as it allows one to create half-initialized object.The best solution would be to take advantage of parametrized
<lookup-method/>– feature that waits to be implemented in Spring: SPR-7431. Don’t forget to vote and comment!