Wednesday, May 27, 2015

Advantages of Spring Framework

There are many advantages of Spring frame work . Like these are following .

Spring framework provides templates for Hibernate ,JPA etc .. So there is no need to write too much of code .It hides the basic steps of these technologies .

1. Predefined Templates :
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 save a lot of JDBC code.
2. Loose Coupling .
Spring applications are loosely coupled because of dependency injection .
3.Easy to Test :
The dependency injection makes easier to test the application . The EJB strus application requires to server to run the application but spring f/w doesn't require for the server .
4. Light weight :
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 Deployment 
The Dependency Injection feature of Spring Framework and it support to various frameworks makes the easy development of JavaEE application.
6. Powerful Abstraction :
It provides powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA and JTA.
7. Declarative Support :
It provides declarative support for caching, validation, transactions and formatting.

Spring Modules :

Spring modules



Test : This Layer provides for the testing of our application via Junit and TestNG .

Spring Core Container : It contains Core , beans , context ,expression language (EL) modules .
Context : This module supports Internationalization(i18n), JMS ,Basic Remoting.
Core and beans : Provides Dependency injection feature of our beans .
Expression language
It is an extension of EL defined in JSP . It supports to setting and getting the property of values ,method invocation , accessing the collections and indexers ,named variables ,logical and arithmetical operators ,retrieval of objects by name ..etc .
AOP and Aspects Instrumentation :
This module supports aspect oriented programming implementation where you can use advice , Pointcuts etc to decouple the code.
this module integration's with AspectJ .
The instrumentation module provides support to class instrumentation and classloader implementations.
Data Access /Integration :
This group comprises the JDBC, ORM ,OXM ,JMS and Transaction Module. its basically supports to interact with the  Database .
Web :
This group comprises of Web, Web-Servlet, Web-Struts and Web-Portlet. These modules provide support to create web application.

Creating spring application in Eclipse IDE
  1. Here, we are going to create a simple application of spring framework using eclipse IDE. Let's see the simple steps to create the spring application in Eclipse IDE.
  • create the java project
  • add spring jar files
  • create the class
  • create the xml file to provide the values
  • create the test class

Steps to create spring application in Eclipse IDE:


Let's see the 5 steps to create the first spring application using eclipse IDE.

1) Create the Java Project


Go to File menu - New - project - Java Project. Write the project name e.g. firstspring - Finish. Now the java project is created.

2) Add spring jar files

There are mainly three jar files required to run this application.
  • org.springframework.core-3.0.1.RELEASE-A
  • com.springsource.org.apache.commons.logging-1.1.1
  • org.springframework.beans-3.0.1.RELEASE-A
For the future use, You can download the required jar files for spring core application.
To run this example, you need to load only spring core jar files.
To load the jar files in eclipse IDE, Right click on your project - Build Path - Add external archives - select all the required jar files - finish..

3) Create Java class

In such case, we are simply creating the Student class have name property. The name of the student will be provided by the xml file. It is just a simple example not the actual use of spring. We will see the actual use in Dependency Injection chapter. To create the java class, Right click on src - New class - Write the class name e.g. Student - finish. Write the following code:
  1. package com.demo;  
  2.   
  3. public class Student {  
  4. private String name;  
  5.   
  6. public String getName() {  
  7.     return name;  
  8. }  
  9.   
  10. public void setName(String name) {  
  11.     this.name = name;  
  12. }  
  13.   
  14. public void displayInfo(){  
  15.     System.out.println("Hello: "+name);  
  16. }  
  17. }  
This is simple bean class, containing only one property name with its getters and setters method. This class contains one extra method named displayInfo() that prints the student name by the hello message.

4) Create the xml file

To create the xml file click on src - new - file - give the file name such as applicationContext.xml - finish. Open the applicationContext.xml file, and write the following code:
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans  
  3.     xmlns="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xmlns:p="http://www.springframework.org/schema/p"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  7.                http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
  8.   
  9. <bean id="studentbean" class="com.demo.Student">  
  10. <property name="name" value="Vimal Jaiswal"></property>  
  11. </bean>  
  12.   
  13. </beans>  
The bean element is used to define the bean for the given class. The property subelement of bean specifies the property of the Student class named name. The value specified in the property element will be set in the Student class object by the IOC container.

5) Create the test class

Create the java class e.g. Test. Here we are getting the object of Student class from the IOC container using the getBean() method of BeanFactory. Let's see the code of test class.
  1. package com.demo;  
  2.   
  3. import org.springframework.beans.factory.BeanFactory;  
  4. import org.springframework.beans.factory.xml.XmlBeanFactory;  
  5. import org.springframework.core.io.ClassPathResource;  
  6. import org.springframework.core.io.Resource;  
  7.   
  8. public class Test {  
  9. public static void main(String[] args) {  
  10.     Resource resource=new ClassPathResource("applicationContext.xml");  
  11.     BeanFactory factory=new XmlBeanFactory(resource);  
  12.       
  13.     Student student=(Student)factory.getBean("studentbean");  
  14.     student.displayInfo();  
  15. }  
  16. }  
Now run this class. You will get the output Hello: Vimal Jaiswal.
spring with eclipse IDE

IoC Container

to instantiate the application classThe 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 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.ApplicationContextinterfaces 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:
  1. Resource resource=new ClassPathResource("applicationContext.xml");  
  2. 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:
  1. ApplicationContext context =   
  2.     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 LookupDependency 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. To understand the DI better, Let's understand the Dependency Lookup (DL) first:

The Dependency Lookup is an approach where we get the resource after demand. There can be various ways to get the resource for example:
  1. A obj = new AImpl();  
In such way, we get the resource(instance of A class) directly by new keyword. Another way is factory method:
  1. A obj = A.getA();  
This way, we get the resource (instance of A class) by calling the static factory method getA().
Alternatively, we can get the resource by JNDI (Java Naming Directory Interface) as:
  1. Context ctx = new InitialContext();  
  2. Context environmentCtx = (Context) ctx.lookup("java:comp/env");  
  3. A obj = (A)environmentCtx.lookup("A");  
There can be various ways to get the resource to obtain the resource. Let's see the problem in this approach.

Problems of Dependency Lookup

There are mainly two problems of dependency lookup.
  • tight coupling The dependency lookup approach makes the code tightly coupled. If resource is changed, we need to perform a lot of modification in the code.
  • Not easy for testing This approach creates a lot of problems while testing the application especially in black box testing.

Dependency Injection

The Dependency Injection is a design pattern that removes the dependency of the programs. In such case we provide the information from the external source such as XML file. It makes our code loosely coupled and easier for testing. In such case we write the code as:
  1. class Employee{  
  2. Address address;  
  3.   
  4. Employee(Address address){  
  5. this.address=address;  
  6. }  
  7. public void setAddress(Address address){  
  8. this.address=address;  
  9. }  
  10.   
  11. }  
In such case, instance of Address class is provided by external souce such as XML file either by constructor or setter method.

Two ways to perform Dependency Injection in Spring framework

Spring framework provides two ways to inject dependency
  • By Constructor
  • By Setter method

5 comments:

  1. Thanks for sharing this informative content , Great work
    Leanpitch provides online training in Agile coach during this lockdown period everyone can use it wisely.
    Certified agile coaching Bangalore

    ReplyDelete
  2. Thanks for sharing this informative content , Great work
    Leanpitch provides online training in Product prototyping during this lockdown period everyone can use it wisely.
    icp-cat training

    ReplyDelete
  3. Thanks for sharing this informative content , Great work
    To crack scrum master interview : Scrum Master Interview Questions

    ReplyDelete
  4. Thanks for sharing this informative content , Great work
    Leanpitch provides online training in ICP CAT during this lockdown period everyone can use it wisely.
    ICP-CAT certification

    ReplyDelete
  5. Thanks for the blog article.Much thanks again. Fantastic.
    java course
    learn java online

    ReplyDelete

Java 9 and Java11 and Java17, Java 21 Features

 Java 9 and Java11 and Java17 features along with explanation and examples in realtime scenarios Here's a detailed breakdown of Java 9, ...