Springs - SPLessons
boy2 Chapter 10

Spring Bean

Springs - SPLessons

Spring Bean

shape Description

The Spring Bean is a core component that is managed, instantiated by Spring Inversion of control.The Spring Bean will be created with configuration meta data that supply to the container. Spring Bean will have information that is configuration metadata. Configuration meta data is used to know the following.

Above configuration meta data translates into the properties that sharps each bean.The properties are as follows.

Properties Functionality
Class Plays the role to create bean.
Name It is a XML attribute used to indicate the Bean identifier.
Scope Scope of the object will declared here from the bean definition.
constructor-args Dependencies injection will be done by constructor-args.
Properties Involves in injection of dependencies.
Auto-wiring mode Involves in injection of dependencies.
Lazy-initialization mode Bean instance will be created by IOC when Lazy-initialization mode is first requested.
Initialization method If all the properties of bean are perfectly set by the IOC then it will be callback.
Destruction method After destruction callback will be useful.

Spring Configuration Metadata

Metadata describes the code which written by developer, generally metadata will be stored inside the comments, but it is not used by the developer. If metadata is presented in XML or Annotation files it will be used to application development.

XML  configuration with bean properties are as follows.

<?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-3.0.xsd">

   <!-- A simple bean definition -->
   <bean id="..." class="...">
       <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- A bean definition with lazy init set on -->
   <bean id="..." class="..." lazy-init="true">
       <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- A bean definition with initialization method -->
   <bean id="..." class="..." init-method="...">
       <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- A bean definition with destruction method -->
   <bean id="..." class="..." destroy-method="...">
       <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- more bean definitions go here -->

</beans>

Spring Bean Life Cycle

shape Description

In bean life cycle components will have their own functionalities. When the bean is initiated some initialization work needs to be performed to get into active state and the same thing will be done at destroy state like when a bean is not required it ought to be removed in the framework. Spring bean life cycle as shown as follows.

shape Conceptual
Figure

Initialization callbacks

shape Description

In the life cycle of bean background work will be done with the help of init-method and destroy method. Before the start of the bean initialization work init-method will be used.

org.springframework.beans.factory.InitializingBean interface give Initialization callbacks technique as shown.

void afterPropertiesSet() throws Exception;

So interface has to be actualized essentially and introduction work should be possible inside afterPropertiesSet() technique shown as follows.

public class ExampleBean implements InitializingBean {
   public void afterPropertiesSet() {
      // do some initialization work
   }
}


Destruction callbacks

shape Description

void destroy() throws Exception;

In the life cycle of bean background work will be done with the help of init-method and destroy method. Before bean is removed from the framework container it will be used.

public class ExampleBean implements DisposableBean {
   public void destroy() {
      // do some destruction work
   }
}

Spring Bean Scope

shape Description

While defining a bean, developer will have the option to describe the scope of the bean. The spring framework will support the following five scopes.

  • Singleton:A singleton is by default scope if the developer doesn’t mention scope which means there one instance per Spring container.
  • Prototype:Instead of having one instance per container, with prototype developer gets a new instance per request.
  • Request:This scope depends on the HTTP request.
  • Session:This scope depends on the HTTP session.
  • Global-session:This scope depends on the global HTTP session. This scope will be available in a web-aware Spring ApplicationContext.

The Singleton Scope

A singleton is by default scope if the developer doesn’t mention scope which means there one instance per Spring container.

<!-- A bean definition with singleton scope -->
<bean id="..." class="..." scope="singleton">
    <!-- collaborators and configuration for this bean go here -->
</bean>

Each bean will consists of unique id in the container. Id can not contain special characters like ‘/’ and pattern matching like ‘/*. html’. But name property can follow this feature best form spring move. Name property can set with special characters like “/*. html”. Which is directly called in the URL also.

Helloword.Java 

package splessons;

public class HelloWorld {
   private String message;

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

   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}


Here the developer just created data member and performed SET and GET methods to get the data.
MainApp.Java 

package splessons;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

      HelloWorld h1 = (HelloWorld) context.getBean("helloWorld");

      h1.setMessage("SPLESSONS");
      h1.getMessage();

      HelloWorld h2 = (HelloWorld) context.getBean("helloWorld");
      h2.getMessage();
   }
}

The Application Context is spring’s more best in class holder. Like BeanFactory it can stack bean definitions, wire beans together and administer beans upon solicitation. Also it includes more enterprise-specific usefulness, for example, the capacity to determine literary messages from a properties document and the capacity to distribute application events to interested event listeners. This container is characterized by the org.springframework.context.ApplicationContext interface.
Beans.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-3.0.xsd">

   <bean id="helloWorld" class="splessons.HelloWorld" 
      scope="singleton">
   </bean>

</beans>

Output 

Your Message :SPLESSONS 
Your Message :SPLESSONS 

The Prototype Scope

In case of prototype scope, some pool will be maintained by core container. It will serve the bean instance from that pool. Example as follows.

Helloword.Java

package splessons;

public class HelloWorld {
   private String message;

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

   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}

MainApp.Java 

package splessons;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

      HelloWorld objA = (HelloWorld) context.getBean("helloWorld");

      objA.setMessage("SPLESSONS");
      objA.getMessage();

      HelloWorld objB = (HelloWorld) context.getBean("helloWorld");
      objB.getMessage();
   }
}

The classpath syntax means that Spring will search the classpath for all resources called /META-INF/spring.xml and myapplication-application-context.xml, and will amalgamate them into the context. This includes looking through JAR files inside the project, so there may not be any visible within your main project files.
Beans.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-3.0.xsd">
  <bean id="helloWorld" class="splessons.HelloWorld" scope="singleton">
   </bean>

</beans>

Output

Your Message :SPLESSONS 
Your Message :null 

Summary

shape Key Points

  • Request scope returns a single bean per one HTTP request.
  • Session scope returns a single bean per one HTTP session.