When not to use Spring to instantiate a bean?
- by Rishabh
I am trying to understand what would be the correct usage of Spring. Not syntactically, but in term of its purpose.
If one is using Spring, then should Spring code replace all bean instantiation code?
When to use or when not to use Spring, to instantiate a bean?
May be the following code sample will help in you understanding my dilemma:
List<ClassA> caList = new ArrayList<ClassA>();
for (String name : nameList) {
ClassA ca = new ClassA();
ca.setName(name);
caList.add(ca);
}
If I configure Spring it becomes something like:
List<ClassA> caList = new ArrayList<ClassA>();
for (String name : nameList) {
ClassA ca = (ClassA)SomeContext.getBean(BeanLookupConstants.CLASS_A);
ca.setName(name);
caList.add(ca);
}
I personally think using Spring here is an unnecessary overhead, because
The code the simpler to read/understand.
It isn't really a good place for Dependency Injection as I am not expecting that there will be multiple/varied implementation of ClassA, that I would like freedom to replace using Spring configuration at a later point in time.
Am I thinking correct? If not, where am I going wrong?