CHAPTER 5: Building Java Web Applications with Spring Web MVC 207
As illustrated in Figure 5-1, the Spring IoC container produces fully configured application objects by
using application POJO objects and configuration metadata.
Application POJO objects: In Spring, the application objects that are managed
by the Spring IoC container are called beans. A Spring bean is an object that is
instantiated, assembled, and managed by a Spring IoC container.
Note In Spring, components are also called beans. The Spring beans are different from the JavaBeans
convention. The Spring beans can be any plain old Java objects (POJOs). A POJO is an ordinary Java object
without any specific requirements, such as extending a specific class or implementing a specific interface.
Configuration metadata: The configuration metadata specifies the objects that
comprise your application and the interdependencies between such objects.
The container reads the configuration metadata and figures out from it which
objects to instantiate, configure, and assemble. The container then injects those
dependencies when it creates the bean. The configuration metadata can be
represented by either XML, annotations, or Java code.
In terms of implementation, the Spring container can inject objects in arguments of instance and
static methods and can inject constructors via dependency injection. Say you have an application
that has a component called ClassA that depends on ClassB. In other words, ClassB is the
dependency. Your standard code would look like Listing 5-1.
Listing 5-1. Tightly Coupled Dependency
- public class ClassA {
- private ClassB classB;
- public ClassA() {
- classB = new ClassB();
- }
- }
We create a dependency between ClassA and ClassB in line 3-4 of Listing 5-1. This tightly couples
ClassA with ClassB. This tight coupling can be circumvented using IoC, and in order to that, first we
need to change the code in Listing 5-1 to Listing 5-2.
Listing 5-2. Removing the Tight Coupling Between ClassA and ClassB
- public class ClassA {
- private ClassB classB;
- public ClassA(ClassB classB) {
- this.classB = classB;
- }
- }
As you can see in Listing 5-2, ClassB is implemented independently, and the Spring container
provides this implementation of ClassB to ClassA at the time of instantiation of ClassA, and the
dependency (in other words, class ClassB) is injected into class ClassA through a constructor. Thus,