Monday, August 8, 2016

Spring Tutorial

Spring is a light weight and open source framework created by Rod Johnson in2003. Spring is a complete and a modular framework, I mean spring framework can be used for all layer implementations for a real time application or spring can be used for the development of particular layer of a real time application unlike struts [ only for front end related] and hibernate [ only for database related], but with spring we can develop all layers

Spring Framework
Spring is a lightweight framework. because it provides support to various frameworks such as Struts, Hibernate, Tapestry, EJB, JSF etc. The framework, in broader sense, can be defined as a structure where we find solution of the various technical problems.
The Spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM, WEB MVC etc.

Inversion Of Control (IOC) and Dependency Injection
These are the design patterns that are used to remove dependency from the programming code. They make the code easier to test and maintain. Let's understand this with the following code:
class Employee{  
Address address;  
Employee(){  
address=new Address();  
}  
}  
In such case, there is dependency between the Employee and Address (tight coupling). In the Inversion of Control scenario, we do this something like this:
class Employee{  
Address address;  
Employee(Address address){  
this.address=address;  
}  
}  
Thus, IOC makes the code loosely coupled. In such case, there is no need to modify the code if our logic is moved to new environment.
In Spring framework, IOC container is responsible to inject the dependency. We provide metadata to the IOC container either by XML file or annotation.

Advantage of Dependency Injection
  • makes the code loosely coupled so easy to maintain
  • makes the code easy to test
 Advantages of Spring Framework
There are many advantages of Spring Framework. They are as follows:
1) Predefined Templates
Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies. So there is no need to write too much code. It hides the basic steps of these technologies.
Let's take the example of JdbcTemplate, you don't need to write the code for exception handling, creating connection, creating statement, committing transaction, closing connection etc. You need to write the code of executing query only. Thus, it saves a lot of JDBC code.

2) Loose Coupling
The Spring applications are loosely coupled because of dependency injection.

3) Easy to test
The Dependency Injection makes easier to test the application. The EJB or Struts application require server to run the application but Spring framework doesn't require server.

4) Lightweight
Spring framework is lightweight because of its POJO implementation. The Spring Framework doesn't force the programmer to inherit any class or implement any interface. That is why it is said non-invasive.

5) Fast Development
The Dependency Injection feature of Spring Framework and it support to various frameworks makes the easy development of J2EE application.

6) Powerful abstraction
It provides powerful abstraction to J2EE specifications such as JMS, JDBC, JPA and JTA.

7) Declarative support
It provides declarative support for caching, validation, transactions and formatting.

IoC Container
The IoC container is responsible to instantiate, configure and assemble the objects. The IoC container gets informations from the XML file and works accordingly. The main tasks performed by IoC container are:
  • to instantiate the application class
  • to configure the object
  • to assemble the dependencies between the objects
There are two types of IoC containers. They are:
  1. BeanFactory
  2. ApplicationContext

Difference between BeanFactory and the ApplicationContext
The org.springframework.beans.factory.BeanFactory and the org.springframework.context.ApplicationContext interfaces acts as the IoC container. The ApplicationContext interface is built on top of the BeanFactory interface. It adds some extra functionality than BeanFactory such as simple integration with Spring's AOP, message resource handling (for I18N), event propagation, application layer specific context (e.g. WebApplicationContext) for web application. So it is better to use ApplicationContext than BeanFactory.

Using BeanFactory
The XmlBeanFactory is the implementation class for the BeanFactory interface. To use the BeanFactory, we need to create the instance of XmlBeanFactory class as given below:
Resource resource=new ClassPathResource("applicationContext.xml");  
BeanFactory factory=new XmlBeanFactory(resource);  
The constructor of XmlBeanFactory class receives the Resource object so we need to pass the resource object to create the object of BeanFactory.

Using ApplicationContext
The ClassPathXmlApplicationContext class is the implementation class of ApplicationContext interface. We need to instantiate the ClassPathXmlApplicationContext class to use the ApplicationContext as given below:
ApplicationContext context =   
new ClassPathXmlApplicationContext("applicationContext.xml");  
The constructor of ClassPathXmlApplicationContext class receives string, so we can pass the name of the xml file to create the instance of ApplicationContext.

Dependency Injection in Spring
Dependency Injection (DI) is a design pattern that removes the dependency from the programming code so that it can be easy to manage and test the application. Dependency Injection makes our programming code loosely coupled.

Two ways to perform Dependency Injection in Spring framework
Spring framework provides two ways to inject dependency
  • By Constructor
  • By Setter method
 Dependency Injection by Constructor Example
We can inject the dependency by constructor. The sub element of  is used for constructor injection. Here we are going to inject
  1. primitive and String-based values
  2. Dependent object (contained object)
  3. Collection values etc.
 Injecting primitive and string-based values
Let's see the simple example to inject primitive and string-based values. We have created three files here:
  • Employee.java
  • applicationContext.xml
  • Test.java
 Employee.java
It is a simple class containing two fields id and name. There are four constructors and one method in this class.
public class Employee {  
private int id;  
private String name;  
  
public Employee() {System.out.println("def cons");}  
public Employee(int id) {this.id = id;}  
public Employee(String name) {  this.name = name;}  
public Employee(int id, String name) {  
    this.id = id;  
    this.name = name;  
}  
void show(){  
    System.out.println(id+" "+name);  
}  
}  
applicationContext.xml
We are providing the information into the bean by this file. The constructor-arg element invokes the constructor. In such case, parameterized constructor of int type will be invoked. The value attribute of constructor-arg element will assign the specified value. The type attribute specifies that int parameter constructor will be invoked.

 

Test.java
This class gets the bean from the applicationContext.xml file and calls the show method.
public class Test {  
    public static void main(String[] args) {  
        Resource r=new ClassPathResource("applicationContext.xml");  
        BeanFactory factory=new XmlBeanFactory(r);  
        Employee s=(Employee)factory.getBean("e");  
        s.show();  
    }  
}  
Output:10 null

Dependency Injection by setter method
We can inject the dependency by setter method also. The subelement of  is used for setter injection. Here we are going to inject
  1. primitive and String-based values
  2. Dependent object (contained object)
  3. Collection values etc.
Injecting primitive and string-based values by setter method
Let's see the simple example to inject primitive and string-based values by setter method. We have created three files here:
  • Employee.java
  • applicationContext.xml
  • Test.java
Employee.java
It is a simple class containing three fields id, name and city with its setters and getters and a method to display these informations.
public class Employee {  
private int id;  
private String name;  
private String city;  
  // setters and getters
void display(){  
    System.out.println(id+" "+name+" "+city);  
}  
}  
applicationContext.xml
We are providing the information into the bean by this file. The property element invokes the setter method. The value subelement of property will assign the specified value.

Test.java
This class gets the bean from the applicationContext.xml file and calls the display method.
public class Test {  
   public static void main(String[] args) {  
      Resource r=new ClassPathResource("applicationContext.xml");  
       BeanFactory factory=new XmlBeanFactory(r);  
        Employee e=(Employee)factory.getBean("obj");  
        s.display();  
    }  
}  
Output:20 Arun ghaziabad

No comments:

Post a Comment