Spring Tutorial – Learn Spring Framework step by step

Spring Tutorial provides basic and advanced concepts of Spring Framework. Our Spring Tutorial is designed for beginners and professionals both. In this spring tutorial, you will learn the spring framework with examples and simple steps, it provides many steps by step examples and explanations on using the Spring framework. The Spring framework, created by Rod Johnson, is an extremely powerful Inversion of control(IoC) framework to help decouple your project components’ dependencies.

Spring Tutorial

Background of Spring and the Spring Framework

In this Spring Tutorial first let’s discuss some history of the Spring Framework as below:
On Oct 2002– The first version released on the book (Expert One-on-One J2EE Design and Development) by Rod Johnson. In 2003, Spring came into existence as a solution to the complexity of the early J2EE specifications. It is complementary to Java EE. The Spring programming model integrates only with selected individual specifications such as Servlet API, JPA, JMS, Bean Validation, JSON Binding API, Concurrency Utilities, WebSocket API and JTA/JCA setups for transaction coordination. Let’s see the following list.
  • On Jun 2003– Take license from Apache and First released as a Framework.
  • Jan 2006- Won the two awards Jolt productivity award and JAX Innovation Award.
  • On Oct 2006Spring 2.0 released.
  • On Nov 2007Spring 2.5 released.
  • On Dec 2009Spring 3.0 released.
  • On Dec 2011Spring 3.1 released.
  • On Jun 2012Spring 3.2 released.
  • On December 2013Spring 4.0 released.
  • On 31 July 2015Spring 4.2 released.
  • On 10 June 2016Spring 4.3 released.
  • Next, Spring 5 is announced to be built upon Reactive Streams compatible Reactor Core. For Spring Framework 5.0, Spring must have Java EE 7 level as a minimum requirement. It is fully compatibles with Tomcat 8/9, JBoss EAP 7 and WebSphere 9.

Let’s move to more about the Spring Framework in the Spring tutorial.

Spring 5 Design Pattern Book

This Spring tutorial provides you with a lot of simple examples, beginners can learn the Spring Framework easily with this Spring tutorial. But you want more insight about the Spring framework and new features of the Spring 5. You could purchase my Spring 5 book that is with title name “Spring 5 Design Pattern“. This book is available on the Amazon and Packt publisher website. Learn various design patterns and best practices in Spring 5 and use them to solve common design problems. You could use an author discount to purchase this book by using code- “AUTHDIS40“.
Spring-5-Design-Pattern

Spring Tutorial: What is Spring?

A Java application framework which allows the user to create a Java enterprise application with inversion of control container is known as Spring Framework. The Spring Framework is open source with extensions for building web applications on the top of the Java EE (Enterprise Edition) platform.

Plain Old Java Objects (POJOs) can be built from Spring with enterprise services non-invasively. Following are some examples to the Java SE programming model:

  • A Java method can be created in a database without the interaction of APIs
  • A remote procedure of local Java without involving remove APIs
  • A Java method for a message handler without JMS (Java Messaging Service) APIs
  • A management operation by a local Java method without JMX (Java Management Extensions) APIs

Spring is a great framework for the development of Enterprise grade applications. It is a light-weight framework for the development of enterprise-ready applications. It provides very simple and rich facilities to integrate various frameworks, technologies, and services in the applications. One of the main reason for using the Spring framework is to keep the code as simple as possible. It pushes the way to develop enterprise applications with loosely coupled simple java beans. For this reason, the spring framework can also be called a Plain Old Java Object (POJO) framework.

Let’s see the next section about the modules in the Spring framework. This Spring tutorial explains a lot of major modules of the Spring Framework.

Modules in Spring Framework

The Spring Framework has been categorized into modules. All modules will not be used in an application, so every module is dependent on the type of application. There are 20 modules organized in Spring Framework. Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation and Test are the groups.

A configuration model and a dependency injection mechanism belong to the core container located in the heart of the framework. Beyond that, there are different application architectures such as transactional data, messaging, persistence and web for the foundational support. Servlet-based Spring MVC web-framework is also there in parallel with the Spring WebFlux reactive web framework.

Spring modules

Spring is an open-source framework developed by Spring Source, a division of VMware. Spring framework can be summarized in two ways. Let’s see Spring into two parts in this Spring Tutorial.

Part 1: The Core Container

In this Spring tutorial, I have explained the Spring framework as a container and as a framework.

The Core Container has Beans, Core, Context and Expression Language modules.

Core and Beans are the basic parts of the framework with Dependency Injection and IoC features. The BeanFactory is a sophisticated implementation of the factory pattern. There is no need for programmatic singletons and they also allow decoupling the specification and configuration of dependencies from the actual program logic.

Context is another module which is built on the solid base by the Core and Beans. This module is a way to access the objects in a framework-style and is similar to a JNDI registry. It has the features from the Bean modules and supports internationalization, resource-loading, event-propagation and the transparent creation. EJB, JMX and basic remoting are also supported by Java EE in this module. The Context module has a focal point which is known as the ApplicationContext.

The most powerful expression language used for manipulation and querying an object graph at runtime is said to be in the Expression Language. It acts as an extension of the unified expression language in the JSP 2.1 specification. This language helps in setting and getting property values, method invocation, and access of context in arrays, property assignment, logical and arithmetic operators and retrieval of objects.

Spring framework can be described as a lightweight container, as it does not involve installation, configuration, start and stop activities associated with a container. It is just a simple collection of few Java ARchive (JAR) files that need to be added to the classpath. The Spring Container takes the classes in the application, creates objects, and manages the life cycle of those objects.

Let’s move to the second part of the Spring framework in this spring tutorial.

Part 2: The Framework

Spring framework can be described as an Application Programming Interface(API) containing a large collection of the classes, methods, interfaces, annotations, XML tags that can be used in an application. The API provides a variety of factory and facade classes that help you to use any framework or functionality very easily in your application.

The Core package is the most fundamental part of the framework and provides the IoC and Dependency Injection features. The basic concept here is the BeanFactory, which provides a sophisticated implementation of the factory pattern which removes the need for programmatic singletons and allows you to decouple the configuration and specification of dependencies from your actual program logic.

Data Access/Integrations

This layer comprises of OXM, Object Relational Mapping (ORM), Java Database Connectivity (JDBC), JMS and Transaction modules. The OXM module has an abstraction layer that supports mapping implementation for XStream, JiBX, XMLBeans, Castor and JAXB. A JDBC-abstraction layer is formed in the JDBC module which removes the need to do tedious parsing and coding of itself with database-vendor specific error codes. The ORM module is popular due to its integration functionality with iBatis, Hibernate, JDO and JPA.

In this package, the O/R mapping frameworks can be utilized with a combination of features which are supported by Spring, like the simple declarative transaction management feature. For producing and consuming messages, the Java Messaging Service (JMS) module has been built. The implementation of special interfaces in programmatic and declarative transaction management for classes is only found in the Transaction module of POJOs.

Aspect Oriented Programming (AOP)

Aspect-Oriented Programming (AOP) is an approach which allows global properties to define method-interceptors and pointcuts in an executable program. The main aim of this programming paradigm is to increase modularity without modifying the code instead of modifying via point-cut specification. It provides integration with AspectJ. The Instrumentation module has class support and a classloader implementation in certain application servers. It also includes programming methods and tools which support modularization of concerns of the source code.

spring certification

Spring’s MVC

The Web layer is built up of Web-Servlet, Web-Portlet, and Web-Struts. The Web module has ‘multipart file-upload functionality’ as integration features. The initialization of the IoC container can take place using servlet listeners. It also contains a web-oriented application context of Spring’s remoting support. In Web-Servlet module, web applications are implemented by model-view-controller (MVC). This MVC of the Spring framework has both web forms and model code with a clear separation. The Web-Portlet module has the implementation of MVC in a portlet environment and mirrors the functionality of Web-Servlet module. The support classes for integration with a class Struts web tier is only found in the Web-Struts module.

Spring Test

This module covers the testing of Spring components with TestNG or JUnit. It balances the consistency of loading in ApplicationContexts and caching of them in Spring. Mock objects are created to test the code in isolation.

Object XML Mapping

Spring 3.0 introduces the OXM module that was earlier not a part of the core framework. OXM is a mechanism that marshals or converts the object into the XML format and vice versa. There are lots of OXM frameworks, such as Caster, Xstream, JiBX, Java API for XML Binding(JAXP), and XML means. Spring 3.0 provides a uniform API to access any of these OXM frameworks for marshalling and unmarshalling object and XML.

Dependency Injection (DI)

The technology that Spring is most identified with is the Dependency Injection (DI) flavour of Inversion of Control. The Inversion of Control (IoC) is a general concept, and it can be expressed in many different ways and Dependency Injection is merely one concrete example of Inversion of Control.

What is dependency injection exactly?

Let’s look at these two words separately. Here the dependency part translates into an association between two classes. For example, class X is dependent on class Y. Now, let’s look at the second part, injection. All this means is that class Y will get injected into class X by the IoC. Here we don’t need to write lots of code to create the instance of the dependent classes.

Spring Dependency

Dependency injection promotes loose coupling. It paves the way for the removal of the usual factory and utility classes that we write in our applications.
Look Following in this Spring Tutorial:

  • The DAO classes use Data Sources, we can inject it into DAO classes.
  • The Service classes may need to add a few java beans

Dependency Injection is also known as Inversion of Control or IoC.  The IoC refers to the control of creating instances. The container has a responsibility to control for creating and constructing objects. The container creates objects and injects them into our applications. Let’s look into the benefits of Spring Tutorial.

First Program in Spring Framework

In order to develop a code in spring framework, you’ll need to have an eclipse ID and have eclipse software configured in your machine. After it is ready, there are five basic steps to create and run the program:

  1. Create a bean class
  2. XML File
  3. The main method called Demo class
  4. Load jar files
  5. Run the code

There is a class Employee and for this class, there is an ID like employee ID where the employee name is coming in the below code. We will save the address of the employee with other details. Now, we create an object and a reference. We are now calling the constructor and have defined the objects in a conventional way. Spring has a core module which follows inversion of control which is meant by this term inversion of control. Let us now try to understand this core concept.

class Employee {
	// Attributes
	int eid;
	String ename;
	String address;
	char gender;

	//Methods
	//....
}

//Object Construction
Employee eRef = new Employee ();
eRef.eid = 100;
eRef.enam = "Dinesh Rajput";
eRef.address = "Noida";
eRef.gender = "Male";

Spring IOC states that we don’t create objects and now objects will be configured in an XML file. There is one module known as ‘sprint container’ and this module is responsible to construct the Java objects by parsing XML pipe. Here, we are not constructing the objects. They will be constructed by the spring container by parsing the XML file. We need to mention the data which these attributes will store in an XML file which is known as inversion of control. Thus, having control over the object construction is given to the spring container. The benefit of using this is that our XML files are not a part of source code so we can configure and manipulate the values.

Another class is created which is named as Client and it is the main method. The object construction has employee id, employee name, employee address and prints all the details.

public class Client {
	public static void main (string [] args ) {
	//Object construction
	Employee eRef = new Employee ();
	eRef.setEid(100);
	eRef.setEname("Dinesh Rajput);
	eRef.setEaddress("Noida");
	
	system.out.println("Employee Details: "+eRef);
	}
}

The application is run and the output is generated successfully. Now in order to use spring code framework, an XML file is required. Recalling the above five steps, the bean class here in this example is Employee class and the demo class is the Client class. We loaded the jar files and now we need an XML file. We are including that file in our SRC folder of the project. When an XML file is opened, there is a root tag of DS and beans here.

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-2.5.xsd">
<bean id="emp1" class="com.dineshonjava.Employee"> 
<property name="eid" value = "101"/> <property name="ename" value= "Arnav Rajput"/>
<property name="eaddress" value= "New Delhi"/>
</bean>
<bean id="emp1" class="com.dineshonjava.Employee">
 <property name="eid" value = "102"/> 
<property name="ename" value= "Anamika Rajput"/> 
<property name="eaddress" value= "Noida"/>
</bean>  
 </beans>

After adding object details inside the XML file, we will now do the inversion of control. It will write an API, known as a resource from the Spring framework. If we take that interface now, the resource will become a new classpath which will have only the name of the employee. We have given the name of this XML file here and thereafter we got an interface as ravine factory. Bean factory is a new XML factory from the spring core container. It will parse the XML file and construct the objects.

//Spring Way | IOC (Inversion of Control)
Resource resource = new ClassPathResource("spring.xml");
BeanFactory factory = new XMLBeanFactory(resource);
Employee e1 = factory.getBean("emp1");
Employee e2 = factory.getBean("emp2", Employee.class);

Implementation of Inversion of Control in Spring Framework

The Inversion of Control (IoC) is also said to be Dependency Injection (DI) which is a process for objects letting them define their dependencies through construct arguments, a factory method or properties. All of them are set on the object instance returned from a factory method. These dependencies are now injected by the container when it creates the bean.

The process is reversed and itself controlling the instantiation by using the direct construction of classes. The packages org.springframework.context and org.springframework.beans are the main components for IoC container. An advanced configuration mechanism which manages every type of object is known as the BeanFactory interface. The sub-interface of BeanFactory is called ApplicationContext. It is more feasible in adding integration with Spring’s AOP features event publication, message resource handling and application-layer specific contexts, for example, the web applications with the use of WebApplicationContext. The BeanFactory has the configuration framework and the ApplicationContext provides more enterprise-specific functionality. The BeanFactory is a subset of the ApplicationContext.

For example, there is a drawing application which draws different shapes a triangle and a circle in Square. With the code, we can draw certain shapes on the screen. A class Circle is there with object C and the circle object has a draw method and a triangle object. The triangle object has a draw method. Now, all these objects can be used to draw a circle or triangle on the screen. An application class is there where we can instantiate a circle object inside this class and a circle can be drawn by instantiating a triangle object inside the class.

//Circle
draw()
//Triangle
draw()
//Application Class
Triangle myTrianlge = new Triangle();
myTriangle.draw();
Circle myCircle = new Circle();
myCircle.draw();

Polymorphism technique is used here instead of calling the method of the object itself. In the below code, we are handling this parent object and going to call the “draw off the parent” object. Now this parent object could be an abstract class.

//Shape
Share shape = new Triangle();
shape.draw();
Shape shape = new Circle();
Shape.draw();

Instead of having the hard-coded code, we are now writing a method called myDrawMethod and this method is going to take shape as a parameter. Now this shape can draw anything such as a circle or triangle. It just calls the shape and draws now depending on what object we pass to myDrawMethod. In this example, we actually removed the dependency of the circle or triangle from this method, but still, we have to pass this object to myDrawMethod. There has to be another piece of the class which has the initialization, so somebody has to do this shape equal to the new triangle somewhere else in the class. It has to happen this way and then we need to call myDrawMethod by passing this shape. We need to have this new instantiation.

Shape shape = new Triangle();
myDrawMethod(shape);

A drawing class is there which will have a class member variable called shape. It’s not going to be a member variable triangle or member variable of the circle. Actually, it is a member variable of type shape now in the following piece of code:

//Drawing class
protected class Drawing {
private Shape shape;
public setShape (Shape shape) {
	this.shape = shape;
	}
}

//Different class
Trianlge myTrianlge = new Triangle();
drawing.setShape(myTrianlge);
drawing.drawShape();

A class is there which has a private shape object and now a setter is defined here which is public and sets shape object. It can accept both a circle and a triangle as it is a shape object and whatever shape is passed to this object. A method drawshape() is here which draws even it calls a draw method of shape whatever has been set. It will not do an initialization as there is no new shape here, so we are going to assume that somebody will instantiate that and provide an object to this class. Now there is no dependency from a triangle or shape and if we want to draw a triangle, we don’t have to modify the drawing class as it will be going to remain the same.

What we need to do is to pass a triangle to the setter to draw a triangle and vice versa for the circle. We are using a different class which equals new triangle and produce a new object of this drawing class. So now in our drawing class, we have an instance of a specific shape like a triangle or a circle instead of having an instance of a specific shape, it has an instance of the parent shape object. Along with that, we have a different class which has a triangle and then this class is going to pass the triangle to the drawing class. After that, the drawing class is going to have a triangle leaving this class passes a circle to the drawing class which will have a circle. It’s open for a new object to be instantiated as long as the object is a shape so it might draw a new shape.

//Shape
draw()

//Triangle
draw()

The basic concept is to modify this drawing class by passing a corresponding object in a shape and then the drawing class is going to draw it. In this example, we are separating the whole dependency out of a class in which the drawing class doesn’t really know what it’s on the dependent. The advantage of this is that if what it has to draw changes, the user doesn’t have to modify the drawing class because it doesn’t really know any specific shape. It can draw any shape and this is happening because the dependency of the drawing class to a shape object is not owned by the drawing class. There is no relationship, it just has a shape, but does not own any sort of relationship of the actual shape that is drawing. The drawing class has the dependency to the triangle is actually injected into the drawing class by a completely different class so this is the principle of dependency injection here.

Let’s see the next section about the benefits of the Spring framework in the Spring tutorial.

Benefits of Using Spring Framework

Here I have listed following list in this Spring Tutorial of few of the great benefits of using Spring Framework:

  • Spring enables developers to develop enterprise-class applications using POJOs. The benefit of using only POJOs is that you do not need an EJB container product such as an application server but you have the option of using only a robust servlet container such as Tomcat or some commercial product.
  • Spring has multiple modules in a modular fashion. Even though the number of packages and classes are substantial, you have to worry only about ones you need and ignore the rest.
  • Spring does not reinvent the wheel instead, it truly makes use of some of the existing technologies like several ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, other view technologies.
  • Testing an application written with Spring is simple because environment-dependent code is moved into this framework. Furthermore, by using JavaBean-style POJOs, it becomes easier to use dependency injection for injecting test data.
  • Spring’s web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over-engineered or less popular web frameworks.
  • Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.
  • Lightweight IoC containers tend to be lightweight, especially when compared to EJB containers, for example. This is beneficial for developing and deploying applications on computers with limited memory and CPU resources.
  • Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example).

Let’s see below list for the Spring tutorial.

Contents for Spring Tutorial

  1. Dependency Injection in Spring
  2. Setting up the Environment of Spring
  3. Hello World Example in Spring
  4. Spring IoC Container
  5. What is Bean Factory in Spring
  6. Application Context in Spring
  7. Constructor & Object Injecting 
  8. Injecting Inner Beans in Spring with Example
  9. Injecting Collection in Spring
  10. Bean Autowiring in Spring
  11. Understanding Bean Scopes
  12. Using ApplicationContextAware in Spring
  13. Bean Definition Inheritance in Spring
  14. Bean Lifecycle and Callbacks 
  15. Writing a BeanPostProcessor
  16. Writing a BeanFactoryPostProcessor
  17.  Coding To Interfaces in Spring
  18.  Introduction to Annotations and Based Configuration
  19. The Autowired Annotation
  20. Some JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Component and Stereotype Annotations 
  23. Using Property Files by MessageSource in Spring
  24. Event Handling in Spring 
  25. Introduction to AOP in Spring
  26. Setting Up AOP Dependencies
  27. Writing First AspectJ Program in Spring
  28. Pointcuts and Wildcard Expressions  
  29. JoinPoints and Advice Arguments
  30. After Advice Type and Around Advice Type
  31. AOP XML configuration
  32. Understanding AOP Proxies
  33. Spring JDBC Framework
  34. Using JdbcTemplate
  35. Implementing RowMapper 
  36. DAO Support Classes
  37. Transaction Management
  38. Using Hibernate with Spring
  39. Web Framework Spring MVC
  40. Logging with Log4J in Spring Example
  41. Batch Process with Spring and Example
  42. Interview Questions on Spring Framework

I hope this Spring tutorial will be best for your learning. Happy Spring learning.

After learning with this Spring tutorial, you can prepare Spring certification. And test your Spring skill with the following link.

Free Test Practice Spring Core Certification

Previous
Next

16 Comments

  1. Anonymous June 14, 2012
  2. Anonymous September 4, 2012
  3. SEDOTSInfo September 7, 2012
  4. Dinesh Rajput September 9, 2012
  5. Dinesh Rajput September 9, 2012
  6. Dinesh December 30, 2012
  7. Anonymous August 30, 2013
  8. Dinesh August 31, 2013
  9. Vaibhav June 5, 2018
  10. Dinesh Rajput June 15, 2018
  11. Dinesh Rajput June 15, 2018
  12. pushkar September 6, 2018
  13. SARIKA T May 22, 2019
  14. Ganesan Muthukumar May 22, 2019
  15. Dinesh Rajput May 22, 2019
  16. Dinesh Rajput May 22, 2019
  17. Pingback: My Homepage September 15, 2020