Spring Framework (10 Blogs) Become a Certified Professional

Spring Tutorial – A Java Framework Providing Efficiency

Last updated on Dec 18,2023 136.4K Views

Swatee Chand
Sr Research Analyst at Edureka. A techno freak who likes to explore... Sr Research Analyst at Edureka. A techno freak who likes to explore different technologies. Likes to follow the technology trends in market and write...
2 / 5 Blog from Introduction to Spring

Irked of coding too much? Searching for something that is fast, effective and most importantly saves you from writing thousands of lines of code? This blog on Spring Tutorial is about one of the most efficient Java frameworks of all time – Spring Framework. I am pretty much sure that by the time you finish reading this Spring Tutorial blog, you will have good knowledge on Spring Framework. 

Following are the topics I will cover in this Spring Tutorial:

So, let’s get started with the very first topic.

What is Spring Framework and how it works?

Spring - Spring Tutorial - Edureka!

Spring is a powerful lightweight application development framework used for Java Enterprise Edition (JEE). In a way, it is a framework of frameworks because it provides support to various frameworks such as Struts, Hibernate, Tapestry, EJB, JSF, etc. The framework in a broader sense can be defined as a structure using which you can solve many technical problems. You can say that the Spring Framework is a comprehensive tool for supporting applications using Java programming language.

Roderick B. Johnson, an Australian computer specialist officially released the Spring Framework in 2004. Since its origin, the Spring Framework has released many versions. 4.3.8 is the current Spring Framework version.

Features Of Spring Framework

  • Lightweight: Spring Framework is lightweight with respect to size and transparency. 
  • Inversion Of Control (IoC): In Spring Framework, loose coupling is achieved using Inversion of Control. The objects give their own dependencies instead of creating or looking for dependent objects.
  • Aspect Oriented Programming (AOP): By separating application business logic from system services, Spring Framework supports Aspect Oriented Programming and enables cohesive development.
  • Container: Spring Framework creates and manages the life cycle and configuration of application objects.
  • MVC Framework: Spring Framework is a MVC web application framework. This framework is configurable via interfaces and accommodates multiple view technologies.
  • Transaction Management: For transaction management, Spring framework provides a generic abstraction layer. It is not tied to J2EE environments and it can be used in container-less environments.
  • JDBC Exception Handling: The JDBC abstraction layer of the Spring Framework offers an exception hierarchy, which simplifies the error handling strategy.

Why do we use Spring in Java?

  • Works on POJOs (Plain Old Java Object) which makes your application lightweight.
  • Provides predefined templates for JDBC, Hibernate, JPA etc., thus reducing your effort of writing too much code.
  • Because of dependency injection feature, your code becomes loosely coupled.
  • Using Spring Framework, the development of Java Enterprise Edition (JEE) applications became faster.
  • It also provides strong abstraction to Java Enterprise Edition (JEE) specifications. 
  • It provides declarative support for transactions, validation, caching and formatting.

But because of having all these advanced features, often people tend to ask questions like,

Is Spring easy to learn?

So let me answer this question in very simple terms. Yes, Java Spring is really easy to learn as the entire Spring framework is designed to work with POJOs rather than depending on special interfaces, abstract classes, etc.

Elevate your web development skills with our industry-relevant Node JS Course and stay ahead in the ever-evolving tech world.

So, let’s now dive into this Spring Tutorial, starting off from the very basic differences between Java and Spring.

What is the difference between Java and Spring?

The below table represents the differences between Java and Spring:

JavaSpring
Java is one of the prominent programming languages in the market.Spring is a Java-based open-source application framework.
Java provides a full-highlighted Enterprise Application Framework stack called Java EE for web application developmentSpring Framework comes with various modules like Spring MVC, Spring Boot, Spring Security which provides various ready to use features for web application development.
Java EE is built upon a 3-D Architectural Framework which are Logical Tiers, Client Tiers and Presentation Tiers.Spring is based on a layered architecture that consists of various modules that are built on top of its core container.

Since its origin till date, Spring has spread its popularity across various domains. Spring Framework now is the foundation for various other Spring Projects that have come up in the offerings in the last two to three years. Check the below image to find out various projects undertaken by Spring.Spring ecosystem - Spring Tutorial - Edureka

Spring Framework Architecture

As you can see in the diagram below, Spring Framework architecture is an arranged layered architecture that consists of different modules. All the modules have their own functionalities that are utilized to build an application. There are around 20 modules that are generalized into Core Container, Data Access/ Integration, Web, AOP (Aspect Oriented Programming), Instrumentation, and Test. Here, the developer is free to choose the required module. Its modular architecture enables integration with other frameworks without much hassle.

Let’s now explore these modules in detail. I will start with the Core Container on which the rest of the modules are constructed, then I’ll talk about Data Access followed by Web and AOP. Finally, I will discuss some of the miscellaneous modules.  Spring Architecture - Spring Framework Tutorial - Edureka!

Modules Of Spring Framework

Core Container

This container has the following four modules :

  1. Spring Core: This module is the core of the Spring Framework. It provides an implementation for features like  IoC (Inversion of Control) and Dependency Injection with a singleton design pattern.
  2. Spring Bean: This module provides an implementation for the factory design pattern through BeanFactory.
  3. Spring Context: This module is built on the solid base provided by the Core and the Beans modules and is a medium to access any object defined and configured.
  4. Spring Expression Languages (SpEL): This module is an extension to expression language supported by Java server pages. It provides a powerful expression language for querying and manipulating an object graph, at runtime.

Spring Data Access/ Integration

It consists of the following five modules:

  1. JDBC: This module provides JDBC abstraction layer which eliminates the need of repetitive and unnecessary exception handling overhead.
  2. ORM: ORM stands for Object Relational Mapping. This module provides consistency/ portability to our code regardless of data access technologies based on object oriented mapping concept.
  3. OXM: OXM stands for Object XML Mappers. It is used to convert the objects into XML format and vice versa. The Spring OXM provides an uniform API to access any of these OXM frameworks.
  4. JMS: JMS stands for Java Messaging Service. This module contains features for producing and consuming messages among various clients.
  5. Transaction: This module supports programmatic and declarative transaction management for classes that implement special interfaces and for all your POJOs. All the enterprise level transaction implementation concepts can be implemented in Spring by using this module.

Spring Web

Web layer includes the following modules:

  1. Web: This module using servlet listeners and a web-oriented application context, provides basic web-oriented integration features like multi-part file upload functionality and the initialization of the IoC container.
  2. Web-Servlet: This module contains Model-View-Controller (MVC) based implementation for web applications. It provides all other features of MVC, including UI tags and data validations. 
  3. Web-Socket: This module provides support for WebSocket based and two-way communication between the client and the server in web applications.
  4. Web-Portlet: This module is also known as the Spring-MVC-Portlet module. It provides the support for Spring-based Portlets and mirrors the functionality of a Web-Servlet module.

Dive into the world of full stack development and unleash your creativity with our Full Stack Developer Course.

Aspect-Oriented Programming (AOP)

AOP language is a powerful tool that allows developers to add enterprise functionality to the application such as transaction, security etc. It allows us to write less code and separate the code logic. AOP uses cross-cutting concerns.

Instrumentation

This module provides class instrumentation support and classloader implementations that are used in certain application servers.

Test

This module supports the testing of Spring components with JUnit or TestNG. It provides consistent loading of Spring ApplicationContexts and caching of those contexts. It also provides mock objects that we can use to test our code in isolation.

In order to create your application, you might need the help of IDE (Integrated Development Environment). An IDE is a software application that provides comprehensive facilities to the programmers for software development. There are various IDE’s available in the market, here I am using the Eclipse IDE because it’s very convenient to use. So now let’s see how to install IDE and start programming.

You may go through the webinar recording of Spring Tutorial where our instructor has explained the topics in a detailed manner that will help you to understand Spring Framework better.

Spring Tutorial For Beginners With Examples | Edureka

Spring IDE Installation

Note: Before you start installing IDE, you need to have Java installed in your system. In case you want to install Java, refer to this blog.

  1. Go to www.eclipse.org.
  2. Download Eclipse Neon installer and install it on your Windows system.IDE installation - Spring Tutorial - Edureka!
  3. Now you have to install Spring plugin. For that go to Help > Eclipse Marketplace.IDE installation 2- Spring Framework Tutorial - Edureka!
  4. You have to type Spring in the search bar.
  5. Click on “Install”.IDE installation 4 n 5- Spring Tutorial - Edureka!
  6. Now you have to click on “Confirm” to proceed with the installation.Step 6 - Spring Tutorial - Edureka
  7. Let the installation finish, then restart the eclipse although it will automatically ask for it.

First Spring Application

Once you are done with the installation, you are ready to develop your first application in Spring. For that, you need to follow five simple steps:

  1. Create the Bean.java class
  2. Create a XML/ configuration file
  3. Create the main class
  4. Load the required jar files
  5. Run the application

Let’s get started with the first step.

Step I: Creating the Bean class:

  • For this go to File > New > Java Project.
  • Now to create a package, right click on Project > New > package.
  • Name the package and again right click on New > Class.
  • Here is an example of Student bean class.
package org.edureka.firstSpring; 
public class StudentBean 
{ 
String name; public String getName() 
{ return name; } 
public void setName(String name) 
{ this.name = name; } 
public void displayInfo() 
{ System.out.println("Hello: "+ name); } 
}
  • This is a 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 “student name” message.

Step II: Create a XML file

  • Right click on src > New > Other > XML File
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
<bean id="studentbean" class="org/edureka/firstSpring/StudentBean"> 
<property name="name" value="Edureka"></property> 
</bean>
</beans>
  • The <bean> tag is used to define the bean for the given class.
  • The <property> tag is a subelement of bean, and specifies the property of the Student class. The value specified in the property element will be set in the Student class object by the IoC container.

Step III: Create the main class

  • Right click on package > New > Class
  • Here is an example of StudentDemo class:
package org.edureka.firstSpring;
import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 
public class StudentDemo 
{ 
public static void main(String[] args) 
{ 
ApplicationContext appCon=new ClassPathXmlApplicationContext("StudentConfig.xml"); 
StudentBean factory=(StudentBean)appCon.getBean("studentbean"); 
factory.displayInfo(); 
} 
}

Step IV: Load the jar files

  • Here is the list of the jar files needed. You have to download it and add it to your library.

Jar files - Spring Tutorial - Edureka!

NOTE: In case you want jar files, you can comment below.

Step V: Run the program 

  • You can now test your code by running the StudentDemo class. You can see in the below output that the name Edureka is injected by the ApplicationContext at the run-time. Likewise you can change the name any time you want, just by changing the name in the configuration file.

output - Spring Tutorial - Edureka

Spring IoC Container

Since we are done with the first basic program, I hope you have got an idea about Spring Framework. Let’s now discuss on some of the concepts working at the core of Spring Framework. We will begin with IoC container.

So what exactly is an IoC container in Spring? Well, Spring IoC stands for Inversion of Control. It is the heart of the Spring Framework. The important tasks performed by the IoC container are:

  1. Instantiating the bean
  2. Wiring the beans together
  3. Configuring the beans
  4. Managing the bean’s entire life-cycle

 Here is a diagrammatic representation of how beans are wired together by IoC container.

bean wiring - Spring Tutorial - Edureka!

ioc - Spring Tutorial - Edureka!

The IoC container receives metadata from either an XML file, Java annotations, or Java code and works accordingly. IoC adds the flexibility and control of application, and provides a central place of configuration management for Plain Old Java Objects (POJO) of our application. This diagram represents an abstract view of the working of Spring Framework. It shows how Spring makes use of Java POJO classes and configuration metadata to produce a fully configured and executable system or application.

There are two types of IoC containers:

  1. BeanFactory
  2. ApplicationContext

Lets discuss them in detail.

BeanFactory

  • It is an interface defined in org.springframework.beans.factory.BeanFactory.
  • Bean Factory provides the basic support for Dependency Injection.
  • It is based on factory design pattern which creates the beans of any type.
  • BeanFactory follows lazy-initialization technique which means beans are loaded as soon as bean factory instance is created but the beans are created only when getBean() method is called.
  • The XmlBeanFactory is the implementation class for the BeanFactory interface. To use the BeanFactory, you need to create the instance of XmlBeanFactory class as shown below: 
BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("beans.xml"));

ApplicationContext

  • It is an interface defined in org.springframework.context.ApplicationContext.
  • It is the advanced Spring container and is built on top of the BeanFactory interface.
  • ApplicationContext supports the features supported by Bean Factory but also provides some additional functionalities.
  • ApplicationContext follows eager-initialization technique which means instance of beans are created as soon as you create the instance of Application context.
  • The ClassPathXmlApplicationContext class is the implementation class of ApplicationContext interface. You need to instantiate the ClassPathXmlApplicationContext class to use the ApplicationContext as shown below:
ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");

Spring Tutorial: Dependency Injection

Dependency Injection is also one of the core concepts of Spring Framework. It is a design pattern that removes the dependency from the code. That is, the Spring Framework provides the dependencies of the class itself so that it can be easy to manage and test the application. You can provide information from external source such as XML file. Here, you do not create the objects instead you just define how they should be created and IoC container will create the objects for you.

Dependency Injection - Spring Tutorial - Edureka!

In Spring, dependencies can be injected in two ways:

  1. By constructor
  2. By setter method

Lets see how they are done.

By Constructor

  • The <constructor-arg> subelement of <bean> is used for constructor injection. e.g:
<constructor-arg value="101" type="int"></constructor-arg>
  • By default when the Spring container loads the bean, it instantiates the bean with the default constructor. But you can also define a constructor argument in bean definition, using an argument constructor.

By setter method

  • The <property> subelement of <bean> is used for setter injection.e.g:
<property name="id" value="101"></property>
  • Setter-based Dependency Injection is accomplished by the container calling setter methods on your beans after invoking a no-argument.

Spring Tutorial: AOP (Aspect Oriented Programming)

Aspect-oriented programming (AOP) is a programming approach that allows global properties of a program to determine how it is compiled into an executable program. AOP compliments OOPs in the sense that it also provides modularity. But here, the key unit of modularity is an aspect rather than a class. AOP breaks down the logic of program into distinct parts called concerns. This increases modularity by cross-cutting concerns.

A cross-cutting concern is a concern that affects the whole application and is centralized in one location in code like transaction management, authentication, logging, security etc. See the following diagram to understand it better.cross cutting concern - Spring Tutorial - Edureka!AOP can also be considered as a dynamic decorator design pattern. The decorator pattern allows additional behavior to be added to an existing class by wrapping the original class and duplicating its interface and then delegating to the original. You can say that Spring AOP hijacks the executing method, and adds extra functionality before or after the method execution.

Core AOP Concepts 

There are mainly seven core concepts in Aspect Oriented Programming. They are depicted via the following diagram:

AOP Concepts - Spring Tutorial - Edureka!

Let’s discuss them in detail.

  1. Aspect : An aspect is a class that implements the JEE application concerns which cuts through multiple classes, such as transaction management, security etc. Aspects can be a normal class configured through Spring XML configuration. It can also be regular classes annotated using @Aspect annotation.
  2. Joinpoint : A joinpoint is a candidate point in the program execution of an application where an aspect can be plugged in. This point could be a method being called, an exception being thrown, or even a field being modified.
  3. Advice: Advices are the actual actions taken for a particular joinpoint. Basically, they are the methods that get executed when a certain joinpoint meets a matching pointcut in the application.
  4. Pointcut:  Pointcut are expressions that are matched with join points to determine whether advice needs to be executed or not.
  5. Target Object: They are the object on which advices are applied. In Spring AOP, a subclass is created at runtime where the target method is overridden and advices are included based on their configuration.
  6. Proxy: A proxy is an object that is created after applying advice to the target object. In terms of client, the objects, the target object and the proxy object are same.
  7. Weaving: Weaving is the process of linking an aspect with other application types or objects to create an advised object.

AOP Advice Types

advice in AOP - Spring Tutorial - Edureka!

  • Before: These types of advices execute before the joinpoint methods. They are configured using @Before annotation mark.
  • After returning: These types of advices execute after the joinpoint methods complete executing normally. They are configured using @AfterReturning annotation mark.
  • After throwing: These types of advices execute only when joinpoint method exits by throwing an exception. They are configured using @AfterThrowing annotation mark.
  • After (finally): These types of advices execute after a joinpoint method executes, regardless of the method’s exit (whether normal or exceptional return). They are configured using @After annotation mark.
  • Around: These types of advices execute before and after a join point and are configured using @Around annotation mark.

Spring Tutorial: Spring MVC (Model-View-Controller)

Spring MVC helps in building flexible and loosely coupled web applications. The Model-View-Controller design pattern helps in separating the business logic, presentation logic and navigation logic. It provides an elegant solution to use MVC in Spring Framework with the help of DispatcherServlet.

spring mvc - Spring Tutorial - Edureka!

When a request is sent to the Spring MVC Framework, the following takes place.

  • A request is received by DispatcherServlet.
  • The DispatcherServlet communicates with HandlerMapping and calls the Controller associated with the request.
  • The request is processed by the Controller by calling the appropriate service methods and a ModelAndView object to the DispatcherServlet is returned. 
  • The view name is sent to a ViewResolver by the DispatcherServlet to find the actual View to invoke.
  • Now the model object DispatcherServlet is passed to View to render the result.
  • With the help of the model data, the View renders the result back to the user.

So, this brings us to the end of the blog on Spring Tutorial. I tried my best to keep the concepts short and clear. Hope it helped you in understanding Spring Framework and its various features. If you are thinking of seeking your future in Spring, then you can refer to my next blog on Spring Interview Questions. In that blog, I will be discussing questions on various important topics like Spring IoC, Dependency Injection, Annotations, Spring Beans, Spring MVC, AOP etc.

Now that you are done with Spring Tutorial, check out the Spring Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.

Got a question for us? Please mention it in the comments section and we will get back to you.

Comments
20 Comments
  • Rahul111 says:

    I have not yet received jar files.My email id is itsmervp@gmail.com

  • Alyosha Agrawal says:

    class=”org/edureka/firstSpring/StudentBean”> seems incorrect..shouldn’t / be .

    • EdurekaSupport says:

      Hey Rehan, we have sent the Jar files to you. Do let us know if you need anything else. Cheers :)

  • Sai Krishna Padarthi says:

    The article is simply superb. Thanks swatee

    • EdurekaSupport says:

      Hey Sai! We are delighted to know that you found our blogs useful. Do subscribe and stay connected with us. Thanks :)

  • Hemanth says:

    I need those jar files you mentioned in Step IV: Load the jar files

    • EdurekaSupport says:

      Hey Hemant! Drop downn your email ID and we will send the Jar Files with you. Thanks :)

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Spring Tutorial – A Java Framework Providing Efficiency

edureka.co