Java Spring – When Not to Use Spring to Instantiate a Bean

javaspring

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

  1. The code the simpler to read/understand.
  2. 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?

Best Answer

You're right, Spring is inappropriate for the use case you listed. Spring is better used for managing external dependencies (like plugging a JDBC connection into a DAO) or configurations (like specifying which database type to use). In your example, if the bean type was liable to change, then you'd use an interface to specify the bean, and instantiate the beans using a Factory. You'd use Spring to specify which factory to use, and inject that into the class that needed to instantiate the beans. You could then have several different factories that created several different types of beans (that all supported the bean interface), and configure that appropriate one at installation (or update) time.