Monday, October 22, 2012

Basic Bean Creation in Spring


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.

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.

DefaultMessage .java

public class DefaultMessage {
  private String message = "Spring is fun.";
  public String getMessage() {
    return 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.

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()'

Enjoy Creating Beans in Spring :) :) :) 

No comments:

Post a Comment