Friday, April 4, 2014

Spring tutorial 07 - Constructor Injection in the Spring

We have already seen that how to inject property with the Setter Injection in the last blog, now let's go through with the constructor injection.

Configuring bean to initialize with an argument for the constructor and then assign the arguments, Spring essentially “injects” the argument into your bean. This is referred to as constructor injection.
In the constructor Injection an objects gets all its dependencies via constructor.

The most important benefits of Constructor Injection are:


  • It makes a strong dependency contract
  • It makes testing easy, since dependencies can be passed in as Mock Objects
  • It's very succinct in terms of lines of code
  • A dependency may be made immutable by making the dependency reference final





Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.

Let's understand with an example.

Let's create a project say "SpringTutorial" now add the required jar support to spring, to add the jar you can follow the Spring Tutorial 02 -My First 'Hello World' Program in Spring blog.

Now create a package with the name of "org.javaIsEasy.springConstructorInjectionExample".

Now create a java file with the name of "Rectangle.java" in this package.

The Rectangle bean class has two attributes. All the two attributes are set through constructor injection.

Rectangle.java
*******************************************************************************

package org.javaIsEasy.springConstructorInjectionExample;

public class Rectangle {

 private int length;
 private int width;

 Rectangle(int length, int width)
 {
  this.length=length;
  this.width=width;
 }
 public int getLength() {
  return length;
 }

 public int getWidth() {
  return width;
 }

}



*******************************************************************************
Create an other java file in the same package with the name of "Area.java".

In the Area file we will creating object of the Rectangle class and another parameter with the name of 'areaType', we will give the reference of the Rectangle class in this Area class. So let's see how it goes.

Area.java

*******************************************************************************

package org.javaIsEasy.springConstructorInjectionExample;

public class Area {

 private String areaType;
 private Rectangle rectangle;

 public String getAreaType() {
  return areaType;
 }

 public void setAreaType(String areaType) {
  this.areaType = areaType;
 }

 public Rectangle getRectangle() {
  return rectangle;
 }

 public void setRectangle(Rectangle rectangle) {
  this.rectangle = rectangle;
 }


}

*******************************************************************************

Now create another java file with the name of "CallAreaApplication.java" in the same package.
This is the class while having the main method, configuration file will be loaded in this class and let's see how bean is called here.

CallAreaApplication.java
*******************************************************************************

package org.javaIsEasy.springConstructorInjectionExample;

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

public class CallAreaApplication {
public static void main(String[] args) {

 ApplicationContext context = new ClassPathXmlApplicationContext("org/javaIsEasy/springConstructorInjectionExample/Beans.xml");

 Area area=(Area)context.getBean("AreaBean");

 int length=area.getRectangle().getLength();
 int width=area.getRectangle().getWidth();
 String areaType=area.getAreaType();

 System.out.println("Area Name : "+areaType+"\nLength : "+length+"\nWidth : "+width+"\nArea Value : "+length*width);
}
}

*******************************************************************************

Now we have create bean configuration file with the name of "Beans.xml" in the same package. 

Here the Beans.xml file is used to do spring bean configuration. The following code shows how to set a property value through constructor injection.

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="AreaBean" class="org.javaIsEasy.springConstructorInjectionExample.Area">
      <property name="areaType" value="Rectangle"/>
      <property name="rectangle" ref="RectangleBean"/>
   </bean>

 <bean id="RectangleBean" class="org.javaIsEasy.springConstructorInjectionExample.Rectangle">
      <constructor-arg name="length" value="6"/>
      <constructor-arg name="width" value="4"/>
   </bean>
   
</beans>

*******************************************************************************

Structure of the project :





Lets run this program to get the result:

Output:

*******************************************************************************
Area Name : Rectangle
Length : 6
Width : 4
Area Value : 24


*******************************************************************************

Spring tutorial 06 - Setter Injection in the Spring

Setter Injection :

       Spring IOC support the setter injection, which is normally used in the projects. 'set' method is used in the class file to garner property name that are configurable in the config file.

       From a configuration standpoint, setter injection is easier to read because the property name being set is assigned as an attribute to the bean, along with the value being injected. Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

See the example below for basic setter injection on our class.

Let's create a project say "SpringTutorial" now add the required jar support to spring, to add the jar  you can follow the Spring Tutorial 02 -My First 'Hello World' Program in Spring blog.


Now create a package with the name of "org.javaIsEasy.springSetterInjectionExample".
Create a java file in this package with the name of "Area.java".

Area.java

*******************************************************************************
package org.javaIsEasy.springSetterInjectionExample;

public class Area {

 private String areaType;
 private Rectangle rectangle;

 public String getAreaType() {
  return areaType;
 }

 public void setAreaType(String areaType) {
  this.areaType = areaType;
 }

 public Rectangle getRectangle() {
  return rectangle;
 }

 public void setRectangle(Rectangle rectangle) {
  this.rectangle = rectangle;
 }


}

*******************************************************************************

Now create another java file with the name of "Rectangle.java" in the same package.

Rectangle.java
*******************************************************************************
package org.javaIsEasy.springSetterInjectionExample;

public class Rectangle {

 private int length;
 private int width;

 public int getLength() {
  return length;
 }
 public void setLength(int length) {
  this.length = length;
 }
 public int getWidth() {
  return width;
 }
 public void setWidth(int width) {
  this.width = width;
 }


}

*******************************************************************************

Now create another java file with the name of "CallAreaApplication.java" in the same package.

CallAreaApplication.java
*******************************************************************************

package org.javaIsEasy.springSetterInjectionExample;

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

public class CallAreaApplication {
public static void main(String[] args) {

 ApplicationContext context = new ClassPathXmlApplicationContext("org/javaIsEasy/springSetterInjectionExample/Beans.xml");

 Area area=(Area)context.getBean("AreaBean");

 int length=area.getRectangle().getLength();
 int width=area.getRectangle().getWidth();
 String areaType=area.getAreaType();

 System.out.println("Area Name : "+areaType+"\nLength : "+length+"\nWidth : "+width+"\nArea Value : "+length*width);
}
}

*******************************************************************************

Now we have create bean configuration file with the name of "Beans.xml" in the same package. 


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="AreaBean" class="org.javaIsEasy.springSetterInjectionExample.Area">
      <property name="areaType" value="Rectangle"/>
      <property name="rectangle" ref="RectangleBean"/>
   </bean>

 <bean id="RectangleBean" class="org.javaIsEasy.springSetterInjectionExample.Rectangle">
      <property name="length" value="6"/>
      <property name="width" value="4"/>
   </bean>
   
</beans>
*******************************************************************************

Structure of the project :




Lets run this program to get the result:

Output:

*******************************************************************************
Area Name : Rectangle
Length : 6
Width : 4
Area Value : 24


*******************************************************************************

Thursday, April 3, 2014

Spring tutorial 05- Initializing and injecting value in Bean property

To start this blog, lets understand the Beans.

The beans:
A Spring IoC container manages one or more beans. These beans are created using the configuration metadata that has been supplied to the container (typically in the form of XML <bean/> definitions). Beans are represented as beanDefintion objects which contains following meadata.



  • a package-qualified class name: typically this is the actual implementation class of the bean being defined.
  • bean behavioral configuration elements, which state how the bean should behave in the container (scope, lifecycle callbacks, and so forth).
  • references to other beans which are needed for the bean to do its work; these references are also called collaborators or dependencies.
  • other configuration settings to set in the newly created object. An example would be the number of connections to use in a bean that manages a connection pool, or the size limit of the pool.




In Spring, InitializingBean is a marker interface, which is used to initialize the bean.

  • For bean implemented InitializingBean, it will run afterPropertiesSet() after all bean properties have been set
  • For bean implemented DisposableBean, it will run destroy() after Spring container is released the bean.

Example :

In below example we can see, how property can be initialized.

Let's create a project say "SpringTutorial" now add the required jar support to spring, to add the jar  you can follow the Spring Tutorial 02 -My First 'Hello World' Program in Spring blog

Now create a package with the name of "org.javaIsEasy.springPropertyInitializationExample".
Create a java file in this package with the name of "Area.java".

Area.java
*******************************************************************************

package org.javaIsEasy.springPropertyInitializationExample;

public class Area {

private String areaOf;

 public String getAreaOf() {
 return areaOf;
}

public void setAreaOf(String areaOf) {
 this.areaOf = areaOf;
}

 public void calculateArea()
 {
  System.out.println(getAreaOf()+" Area Has been calculated");
 }
}

*******************************************************************************
Now create another file in the same folder with the name of "CallAreaApplication.java".

CallAreaApplication.java
*******************************************************************************

package org.javaIsEasy.springPropertyInitializationExample;

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

public class CallAreaApplication {
public static void main(String[] args) {


 ApplicationContext context=new ClassPathXmlApplicationContext("org/javaIsEasy/springPropertyInitializationExample/Beans.xml");
 Area area=(Area)context.getBean("area");
 area.calculateArea();
}
}

*******************************************************************************

Now at last one more file is need to be created in which we define beans, so let's create "Beans.xml" file in the same folder again.

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="area" class="org.javaIsEasy.springPropertyInitializationExample.Area">
      <property name="areaOf" value="Rectangle"></property>
   </bean>

</beans>

*******************************************************************************

in the above xml file we have injecting the value to the "areaOf" object of the Area class, and giving the value of "Rectangle".

Structure of the project :




Lets run this program to get the result:

Output:

*******************************************************************************
Rectangle Area Has been calculated
*******************************************************************************

Spring Tutorial 04 - Write Spring Program Using ApplicationContext

Before starting program let's get into details of the 'ApplicationContext'.

What is ApplicationContext?

ApplicationContext is an interface for providing configuration information to an application. There are multiple classes provided by springframework that implements this interface and helps us use configuration information in applications.

The lowest level implementation of the IoC container is the BeanFactory, but it is recommended to use an ApplicationContext for your application. The ApplicationContext is a subclass of the BeanFactory interface so it has all the functionality a BeanFactory has and more. Unless you are writing an application that needs an extremely small memory footprint, BeanFactory shouldn't be used directly.




An ApplicationContext provides:


  • ApplicationContext provides all the method of the beanfactory, because it extends BeanFactory.
  • The ability to load file resources in a generic fashion. Inherited from the ResourceLoader interface.
  • The ability to publish events to registered listeners. Inherited from the ApplicationEventPublisher interface.
  • The ability to resolve messages, supporting internationalization. Inherited from the MessageSource interface.
  • Inheritance from a parent context. Definitions in a descendant context will always take priority. 

This means, for example, that a single parent context can be used by an entire web application, while each servlet has its own child context that is independent of that of any other servlet.

public interface ApplicationContext
extends ListableBeanFactory, HierarchicalBeanFactory, MessageSource, ApplicationEventPublisher, ResourcePatternResolver

Above interface is used in Spring.

The most commonly used ApplicationContext implementations are:

FileSystemXmlApplicationContext: This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor.

ClassPathXmlApplicationContext: This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH.

WebXmlApplicationContext: This container loads the XML file with definitions of all beans from within a web application.



Let's create a program to understand the concept of ApplicationContext.

Create a java file with the name of 'Area' inside the package 'org.javaIsEasy.springApplicationContextExample' and copy below code.

Area.java
*******************************************************************************
package org.javaIsEasy.springApplicationContextExample;

public class Area {

 public void calculateArea()
 {
  System.out.println("Area Has been calculated");
 }
}

*******************************************************************************

Create a java file with the name of 'CallAreaApplication' inside the package 'org.javaIsEasy.springApplicationContextExample' and copy below code.

CallAreaApplication.java

*******************************************************************************
package org.javaIsEasy.springApplicationContextExample;

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

public class CallAreaApplication {
public static void main(String[] args) {


 ApplicationContext context=new ClassPathXmlApplicationContext("org/javaIsEasy/springApplicationContextExample/Beans.xml");
 Area area=(Area)context.getBean("area");
 area.calculateArea();
}
}

*******************************************************************************

Create a xml file with the name of 'Beans.xml' inside the package 'org.javaIsEasy.springApplicationContextExample' and copy below code.

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="area" class="org.javaIsEasy.springApplicationContextExample.Area">
      
   </bean>

</beans>

*******************************************************************************
Structure of the project.




Now let's run this program and what results comes. Open 'CallAreaApplication.java' file---> right click---> run as java application.

OUTPUT:
*******************************************************************************
Area Has been calculated
*******************************************************************************