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.
The IoC container is a JavaBean container. JavaBeans in this context are defined simply as reusable modular components – they are complete entities unto themselves. Creating a Spring bean is as simple as coding your POJO (plain old java object) and adding a bean configuration element to the Spring XML configuration file.
To start our tutorial, we'll use a simple POJO, a class called Message which does not have a constructor,
just a setMessage(String message) and getMessage() method. Message has a zero argument constructor and a default message value.
Example 2.1. Basic Bean Creation
package org.springbyexample.springindepth.chapter02.basicBeanCreation;
/**
* Message bean.
*/
public class Message {
protected String message = "Spring comes before summer.";
/**
* 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!).
<?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.springindepth.chapter02.basicBeanCreation.Message" />
</beans>
When the container instantiates this message bean, it is equivalent to initializing an object in your code with 'new Message()'.