When not to use Spring to instantiate a bean?
Posted
by
Rishabh
on Programmers
See other posts from Programmers
or by Rishabh
Published on 2012-10-10T12:16:49Z
Indexed on
2012/10/10
15:54 UTC
Read the original article
Hit count: 296
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?
© Programmers or respective owner