Background of Spring and the Spring Framework
- 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 2006– Spring 2.0 released.
- On Nov 2007– Spring 2.5 released.
- On Dec 2009 – Spring 3.0 released.
- On Dec 2011– Spring 3.1 released.
- On Jun 2012– Spring 3.2 released.
- On December 2013– Spring 4.0 released.
- On 31 July 2015– Spring 4.2 released.
- On 10 June 2016– Spring 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
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 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’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.
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:
- Create a bean class
- XML File
- The main method called Demo class
- Load jar files
- 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
- Dependency Injection in Spring
- Setting up the Environment of Spring
- Hello World Example in Spring
- Spring IoC Container
- What is Bean Factory in Spring
- Application Context in Spring
- Constructor & Object Injecting
- Injecting Inner Beans in Spring with Example
- Injecting Collection in Spring
- Bean Autowiring in Spring
- Understanding Bean Scopes
- Using ApplicationContextAware in Spring
- Bean Definition Inheritance in Spring
- Bean Lifecycle and Callbacks
- Writing a BeanPostProcessor
- Writing a BeanFactoryPostProcessor
- Coding To Interfaces in Spring
- Introduction to Annotations and Based Configuration
- The Autowired Annotation
- Some JSR-250 Annotations
- JSR 330 Annotations in Spring
- Component and Stereotype Annotations
- Using Property Files by MessageSource in Spring
- Event Handling in Spring
- Introduction to AOP in Spring
- Setting Up AOP Dependencies
- Writing First AspectJ Program in Spring
- Pointcuts and Wildcard Expressions
- JoinPoints and Advice Arguments
- After Advice Type and Around Advice Type
- AOP XML configuration
- Understanding AOP Proxies
- Spring JDBC Framework
- Using JdbcTemplate
- Implementing RowMapper
- DAO Support Classes
- Transaction Management
- Using Hibernate with Spring
- Web Framework Spring MVC
- Logging with Log4J in Spring Example
- Batch Process with Spring and Example
- 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.
nice tutorial…
Very very nice and organized tutorial I've ever seen
nice blog, great info
enterprise application
thanks for nice comment and in future various topics on same related to java.. 🙂
thanks .. for comment…:)
good sites
Thanks Dinesh for well laid out tutorials and very good explainations making it easy to understand and follow.
Thanks Friend!!!! Keeping touch with dineshonjava.com and Happy learning.
Regards,
Dinesh
Hi Dinesh,
Is this article updated with Sprint 4.x ?
Thanks
Yes, Vaibhav.
Hi Dinesh,
Can you please explain how we handle multithreading in a web application (especially in spring)?
Hi,
If I follow this blog can I pass Spring Certification?
Thanks,
Sarika
Just now got this link. Very useful.
Thanks, Ganesan.
You can learn a lot of basic things here, for the certification you can also visit spring documentation. For more details, send me a mail admin@dineshonjava.com