A Practical Introduction to Inversion of Control

Susan Kerschbaumer

David Winterfeldt

2009


As we may have mentioned, the core of the Spring Framework is its Inversion of Control (Ioc) container. The IoC container manages java objects – from instantiation to destruction – through its BeanFactory. Java components that are instantiated by the IoC container are called beans, and the IoC container manages a bean's scope, lifecycle events, and any AOP features for which it has been configured and coded.

The IoC container enforces the dependency injection pattern for your components, leaving them loosely coupled and allowing you to code to abstractions. This chapter is a tutorial – in it we will go through the basic steps of creating a bean, configuring it for deployment in Spring, and then unit testing it.

1. Basic Bean Creation

A Spring bean in the IoC container can typically be any POJO (plain old java object). POJOs in this context are defined simply as reusable modular components – they are complete entities unto themselves and the IoC container will resolve any dependencies they may need. Creating a Spring bean is as simple as coding your POJO and adding a bean configuration element to the Spring XML configuration file or annotating the POJO, although XML based configuration will be covered first.

To start our tutorial, we'll use a simple POJO, a class called Message which does not have an explicit constructor, just a getMessage() and setMessage(String message) method. Message has a zero argument constructor and a default message value.

Example 1. DefaultMessage

                
public class DefaultMessage {

    private String message = "Spring is fun.";

    /**
     * Gets message.
     */
    public String getMessage() {
        return message;
    }

    /**
     * Sets message.
     */
    public void setMessage(String message) {
        this.message = message;
    }

}
                
            

The bean element below indicates a bean of type Message – defined by the class attribute – with an id of 'message'. The instance of this bean will be registered in the container with this id.

An end tag for the beans element closes the document (we said it was simple!).

DefaultMessageTest-context.xml
                
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
	   					   http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="message"
          class="org.springbyexample.di.xml.DefaultMessage" />

</beans>
                
            

When the container instantiates the message bean, it is equivalent to initializing an object in your code with 'new DefaultMessage()'.