0% found this document useful (0 votes)
9 views354 pages

Spring SpringBoot

The document provides an overview of the Spring and Spring Boot frameworks, highlighting their importance in Java application development. It explains the distinction between programming languages and frameworks, the advantages of using Spring, and its core features such as dependency injection and inversion of control. Additionally, it covers the architecture of the Spring Framework, its modules, and the benefits of utilizing Spring for enterprise-level applications.

Uploaded by

rahulbadhe630
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
9 views354 pages

Spring SpringBoot

The document provides an overview of the Spring and Spring Boot frameworks, highlighting their importance in Java application development. It explains the distinction between programming languages and frameworks, the advantages of using Spring, and its core features such as dependency injection and inversion of control. Additionally, it covers the architecture of the Spring Framework, its modules, and the benefits of utilizing Spring for enterprise-level applications.

Uploaded by

rahulbadhe630
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 354

Spring & SpringBoot Framework

By –

Dilip Singh
dilipsingh1306@gmail.com

dilipsingh1306

1 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Spring Core Module

2 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Before starting with Spring framework, we should understand more about Programming
Language vs Framework. The difference between a programming language and a framework
is obviously need for a programmer. I will try to list the few important things that students
should know about programming languages and frameworks.

What is a programming language?

Shortly, it is a set of keywords and rules of their usage that allows a programmer to tell a
computer what to do. From a technical point of view, there are many ways to classify
languages - compiled and interpreted, functional and object-oriented, low-level and high-
level, etc..

do we have only one language in our project?

Probably not. Majority of applications includes at least two elements:

➢ The server part. This is where all the "heavy" calculations take place, background API
interactions, Database write/read operations, etc.
Languages Used : Java, .net, python etc..
➢ The client part. For example, the interface of your website, mobile applications, desktop
apps, etc.
Languages Used : HTML, Java Script, Angular, React etc.

Obviously, there can be much more than two languages in the project, especially considering
such things as SQL used for database operations.

What is a Framework?

When choosing a technology stack for our project, we will surely come across such as
framework. A framework is a set of ready-made elements, rules, and components that
simplify the process and increase the development speed. Below are some popular
frameworks as an example:

➢ JAVA : Spring, SpringBoot, Struts, Hibernate, Quarkus etcc..


➢ PHP Frameworks: Laravel, Symfony, Codeigniter, Slim, Lumen
➢ JavaScript Frameworks: ReactJs, VueJs, AngularJs, NodeJs
➢ Python Frameworks: Django, TurboGears, Dash

What kind of tasks does a framework solve?

Frameworks can be general-purpose or designed to solve a particular type of problems.


In the case of web frameworks, they often contain out-of-the-box components for handling:
➢ Routing URLs
➢ Security
➢ Database Interaction,
➢ caching
➢ Exception handling, etc.

3 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Do I need a framework?

➢ It will save time. Using premade components will allow you to avoid reinventing the logics
again and writing from scratch those parts of the application which already exist in the
framework itself.
➢ It will save you from making mistakes. Good frameworks are usually well written. Not
always perfect, but on average much better than the code your team will deliver from
scratch, especially when you're on a short timeline and tight budget.
➢ Opens up access to the infrastructure. There are many existing extensions for popular
frameworks, as well as convenient performance testing tools, CI/CD, ready-to-use
boilerplates for creating various types of applications.

Conclusion:

While a programming language is a foundation, a framework is an add-on, a set of


components and additional functionality which simplifies the creation of applications. In My
opinion - using a modern framework is in 95% of cases a good idea, and it's always a great
idea to create an applications with a framework rather than raw language.

4 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Spring Introduction
The Spring Framework is a popular Java-based application framework
used for building enterprise-level applications. It was developed by Rod
Johnson in 2003 and has since become one of the most widely used
frameworks in the Java ecosystem. The term "Spring" means different
things in different contexts.

The framework provides a comprehensive programming and configuration model for modern
Java-based enterprise applications, with support for features such as dependency injection,
aspect-oriented programming, data access, and transaction management. Spring handles the
infrastructure so you can focus on your application. A key element of Spring is infrastructural
support at the application level: Spring focuses on the "plumbing" of enterprise applications
so that teams can focus on application-level business logic, without unnecessary ties to
specific deployment environments.

One of the key features of the Spring Framework is its ability to promote loose coupling
between components, making it easier to develop modular, maintainable, and scalable
applications. The framework also provides a wide range of extensions and modules that can
be used to integrate with other technologies and frameworks, such as Hibernate, Struts, and
JPA.

Overall, the Spring Framework is widely regarded as a powerful and flexible framework for
building enterprise-level applications in Java.

The Spring Framework provides a variety of features, including:


• Dependency Injection: Spring provides a powerful dependency injection mechanism that
helps developers write code that is more modular, flexible, and testable.
• Inversion of Control: Spring also provides inversion of control (IoC) capabilities that help
decouple the application components and make it easier to manage and maintain them.
• AOP: Spring's aspect-oriented programming (AOP) framework helps developers
modularize cross-cutting concerns, such as security and transaction management.
• Spring MVC: Spring MVC is a popular web framework that provides a model-view-
controller (MVC) architecture for building web applications.
• Integration: Spring provides integration with a variety of other popular Java technologies,
such as Hibernate, JPA, JMS.

Overall, Spring Framework has become one of the most popular Java frameworks due to its
ease of use, modularity, and extensive features. It is widely used in enterprise applications,
web applications, and other types of Java-based projects.

Spring continues to innovate and to evolve. Beyond the Spring Framework, there are other
projects, such as Spring Boot, Spring Security, Spring Data, Spring Cloud, Spring Batch, among
others.

5 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


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.

The Spring Framework includes several modules that provide a range of services:
• Spring Core Container: this is the base module of Spring and provides spring containers
(BeanFactory and ApplicationContext).
• Aspect-oriented programming: enables implementing cross-cutting concerns.
• Data access: working with relational database management systems on the Java platform
using Java Database Connectivity (JDBC) and object-relational mapping tools and
with NoSQL databases
• Authentication and authorization: configurable security processes that support a range
of standards, protocols, tools and practices via the Spring Security sub-project.
• Model–View–Controller: an HTTP- and servlet-based framework providing hooks for web
applications and RESTful (representational state transfer) Web services.
• Testing: support classes for writing unit tests and integration tests

Spring Release Version History:

Version Date Notes


0.9 2003
1.0 March 24, 2004 First production
release.
2.0 2006
3.0 2009
4.0 2013
5.0 2017
6.0 November 16, 2022 Current/Latest Version

6 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Advantages of Spring Framework:
The Spring Framework is a popular open-source application framework for developing
Java applications. It provides a number of advantages that make it a popular choice among
developers. Here are some of the key advantages of the Spring Framework:

1. Lightweight: Spring is a lightweight framework, which means it does not require a heavy
runtime environment to run. This makes it faster and more efficient than other
frameworks.
2. Inversion of Control (IOC): The Spring Framework uses IOC to manage dependencies
between different components in an application. This makes it easier to manage and
maintain complex applications.
3. Dependency Injection (DI): The Spring Framework also supports DI, which allows you to
inject dependencies into your code at runtime. This makes it easier to write testable and
modular code.
4. Modular: Spring is a modular framework, which means you can use only the components
that you need. This makes it easier to develop and maintain applications.
5. Loose Coupling: The Spring applications are loosely coupled because of dependency
injection.
6. Integration: The Spring Framework provides seamless integration with other frameworks
and technologies such as Hibernate, Struts, and JPA.
7. Aspect-Oriented Programming (AOP): The Spring Framework supports AOP, which allows
you to separate cross-cutting concerns from your business logic. This makes it easier to
develop and maintain complex applications.
8. Security: The Spring Framework provides robust security features such as authentication,
authorization, and secure communication.
9. Transaction Management: The Spring Framework provides robust transaction
management capabilities, which make it easier to manage transactions across different
components in an application.
10. Community Support: The Spring Framework has a large and active community, which
provides support and contributes to its development. This makes it easier to find help and
resources when you need them.

Overall, the Spring Framework provides a number of advantages that make it a popular choice
among developers. Its lightweight, modular, and flexible nature, along with its robust features
for managing dependencies, transactions, security, and integration, make it a powerful tool
for developing enterprise-level Java applications.

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.

7 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


What is the difference between Java and Spring?

The below table represents the differences between Java and Spring:

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

Since its origin till date, Spring has spread its popularity across various domains.

Spring Core Module


Core Container:

Spring Core Module has the following three concepts:

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.

Spring Bean:

Beans are java objects that are configured at run-time by Spring IoC Container. In
Spring, the objects of your application and that are managed by the Spring IoC container are
called beans. A bean is an object that is instantiated, assembled, and managed by a Spring IoC
container. Otherwise, a bean is simply one of many objects in your application. Beans, and
the dependencies among them, are reflected in the configuration metadata used by Spring
container.

Dependency Injection in Spring:

Dependency Injection is the concept of an object to supply dependencies of another


object. Dependency Injection is one such technique which aims to help the developer code
easily by providing dependencies of another object. Dependency injection is a pattern we can

8 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


use to implement IoC, where the control being inverted is setting an object's dependencies.
Connecting objects with other objects, or “injecting” objects into other objects, is done by an
container rather than by the objects themselves.

When we hear the term dependency, what comes on to our mind? Obviously, something
relying on something else for support right? Well, that’s the same, in the case of programming
also.

Dependency in programming is an approach where a class uses specific functionalities of


another class. So, for example, If you consider two classes A and B, and say that class A using
functionalities of class B, then its implied that class A has a dependency of class B i.e. A
depends on B. Now, if we are coding in Java then you must know that, you have to create an
instance/Object of class B before the functionalities are being used by class A.

Dependency Injection in Spring can be done through constructors, setters or fields. Here's
how we would create an object dependency in traditional programming:

Employee.java
public class Employee {
private String ename;
private Address addr;

public Employee() {
this.addr = new Address();
}
// setter & getter methods
}

Address.java

public class Address {


private String cityName;
// setter & getter methods
}

In the example above, we need to instantiate an implementation of the Address within


the Employee class itself.

By using DI, we can rewrite the example without specifying the implementation of
the Address that we want:

public class Employee {


private String ename;
private Address addr;

public Employee(Address addr) {


this.addr = addr;

9 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}
}
In the next sections, we'll look at how we can provide the implementation of Address through
metadata. Both IoC and DI are simple concepts, but they have deep implications in the way
we structure our systems, so they're well worth understanding fully.

Spring Container / IOC Container:

An IoC container is a common characteristic of frameworks that implement IoC principle in


software engineering.

Inversion of Control:

Inversion of Control is a principle in software engineering, which transfers the control of


objects of a program to a container or framework. We most often use it in the context of
object-oriented programming.

The IoC container is responsible to instantiate, configure and assemble the objects. The IoC
container gets information’s from the XML file or Using annotations and works accordingly.

The main tasks performed by IoC container are:

• to instantiate the application java classes


• to configure data with the objects
• to assemble the dependencies between the objects internally

As I have mentioned above Inversion of Control is a principle based on which, Dependency


Injection is made. Also, as the name suggests, Inversion of Control is basically used to invert
different kinds of additional responsibilities of a class rather than the main responsibility.

If I have to explain you in simpler terms, then consider an example, wherein you have the
ability to cook. According to the IoC principle, you can invert the control, so instead of you
cooking food, you can just directly order from outside, wherein you receive food at your
doorstep. Thus the process of food delivered to you at your doorstep is called the Inversion
of Control.

You do not have to cook yourself, instead, you can order the food and let a delivery executive,
deliver the food for you. In this way, you do not have to take care of the additional
responsibilities and just focus on the main work.

Spring IOC is the mechanism to achieve loose-coupling between Objects dependencies. To


achieve loose coupling and dynamic binding of the objects at runtime, objects dependencies
are injected by other assembler objects.

Spring provides two types of Container Implementations namely as follows:


1. BeanFactory Container
2. ApplicationContext Container

10 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Spring IoC container is the program that injects dependencies into an object and make it
ready for our use. Spring IoC container classes are part of org.springframework.beans and
org.springframework.context packages from spring framework. Spring IoC container
provides us different ways to decouple the object dependencies. BeanFactory is the root
interface of Spring IoC container. ApplicationContext is the child interface of BeanFactory
interface. These Interfaces are having many implementation classes in same packages to
create IOC container in execution time.

Spring Framework provides a number of useful ApplicationContext implementation


classes that we can use to get the spring context and then the Spring Bean. Some of the useful
ApplicationContext implementations that we use are.

• AnnotationConfigApplicationContext: If we are using Spring in standalone java


applications and using annotations for Configuration, then we can use this to initialize the
container and get the bean objects.
• ClassPathXmlApplicationContext: If we have spring bean configuration xml file in
standalone application, then we can use this class to load the file and get the container
object.
• FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext
except that the xml configuration file can be loaded from anywhere in the file system.
• AnnotationConfigWebApplicationContext and XmlWebApplicationContext for web
applications.

spring is actually a container and behaves as a factory of Beans.

Spring – BeanFactory:

This is the simplest container providing the basic support for DI and defined by the
org.springframework.beans.factory.BeanFactory interface. BeanFactory interface is the
simplest container providing an advanced configuration mechanism to instantiate, configure
and manage the life cycle of beans. BeanFactory represents a basic IoC container which is a
parent interface of ApplicationContext. BeanFactory uses Beans and their dependencies
metadata i.e. what we configured in XML file to create and configure them at run-time.
BeanFactory loads the bean definitions and dependency amongst the beans based on a
configuration file(XML) or the beans can be directly returned when required using Java
Configuration.

Spring ApplicationContext:

The org.springframework.context.ApplicationContext interface represents the Spring IoC


container and is responsible for instantiating, configuring, and assembling the beans. The
container gets its instructions on what objects to instantiate, configure, and assemble by
reading configuration metadata. The configuration metadata is represented in XML, Java
annotations, or Java code. Several implementations of the ApplicationContext interface are
supplied with Spring. In standalone applications, it is common to create an instance of
ClassPathXmlApplicationContext or FileSystemXmlApplicationContext. While XML has been
the traditional format for defining configuration of spring bean classes. We can instruct the

11 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


container to use Java annotations or code as the metadata format by providing a small
amount of XML configuration to declaratively enable support for these additional metadata
formats.

The following diagram shows a high-level view of how Spring Container works. Your
application bean classes are combined with configuration metadata so that, after the
ApplicationContext is created and initialized, you have a fully configured and executable
system or application.

Figure :The Spring IoC container

Configuration Metadata:
As diagram shows, the Spring IoC container consumes a form of configuration
metadata. This configuration metadata represents how you, as an application developer, tell
the Spring container to instantiate, configure, and assemble the objects in your application.
Configuration metadata is traditionally supplied in a simple and intuitive XML format, which
is what most of this chapter uses to convey key concepts and features of the Spring IoC
container. These days, many developers choose Java-based configuration for their Spring
applications.

Instantiating a Container:
The location path or paths supplied to an ApplicationContext constructor are resource
Strings that let the container load configuration metadata from a variety of external
resources, such as the local file system, the Java CLASSPATH, and so on. The Spring provides
ApplicationContext interface: ClassPathXmlApplicationContext and FileSystemXmlApplicatio
nContext for standalone applications, and WebApplicationContext for web applications.

In order to assemble beans, the container uses configuration metadata, which can be in the
form of XML configuration or annotations. Here's one way to manually instantiate a
container:

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

12 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Difference Between BeanFactory Vs ApplicationContext:

BeanFactory ApplicationContext
It is a fundamental container that provides It is an advanced container that extends the
the basic functionality for managing beans. BeanFactory that provides all basic
functionality and adds some advanced
features.
It is suitable to build standalone It is suitable to build Web applications,
applications. integration with AOP modules, ORM and
distributed applications.
It supports only Singleton and Prototype It supports all types of bean scopes such as
bean scopes. Singleton, Prototype, Request, Session etc.
It does not support Annotation based It supports Annotation based configuration in
configuration. Bean Autowiring.
This interface does not provide messaging ApplicationContext interface extends
(i18n or internationalization) functionality. MessageSource interface, thus it provides
messaging (i18n or internationalization)
functionality.
BeanFactory will create a bean object when ApplicationContext loads all the beans and
the getBean() method is called thus making creates objects at the time of startup only
it Lazy initialization. thus making it Eager initialization.

NOTE: Usually, if we are working on Spring MVC application and our application is configured
to use Spring Framework, Spring IoC container gets initialized when the application started or
deployed and when a bean is requested, the dependencies are injected automatically.
However, for a standalone application, you need to initialize the container somewhere in the
application and then use it to get the spring beans.

Create First Spring Core module Application:

NOTE: We can Create Spring Core Module Project in 2 ways.

1. Manually Downloading Spring JAR files and Copying/Configuring Build Path


2. By Using Maven Project Setup, Configuring Spring JAR files in Maven. This is
preferred in Real Time practice.

In Maven Project, JAR files are always configured with pom.xml file i.e. we should not
download manually JAR files in any Project. In First Approach we are downloading JAR files
manually from Internet into our computer and then setting class Path to those jar file, this is
not recommended in Real time projects.

13 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Creation of Project with Downloaded Spring Jar Files :

1. Open Eclipse
File -> new -> Project -> Java Project
Enter Project Name
Un-Select Create Module-Info
Click Finish.

2. Now Download Spring Framework Libraries/jar files from Online/Internet.

I have uploaded copy of all Spring JAR files uploaded in Google Drive. You can download
from below link directly.

https://drive.google.com/file/d/1FnbtP3yqjTN5arlEGeoUHCrIJcdcBgM7/view?usp=dri
ve_link

After Download completes, Please extract .zip file.

14 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


3. Now Please set build path to java project with Spring core jar files from lib folder in
downloaded in step 2, which are shown in image.

Right Click on Project -> Build Path -> Configure Build Path -> Libraries -> ClassPath

With This Our Java Project is Supporting Spring Core Module Functionalities. We can
Continue with Spring Core Module Functionalities.

Creating Spring Core Project with Maven Configuration:

1. Create Java Project.


Open Eclipse -> File -> new -> Project -> Java Project -> Enter Project Name
-> Un-Select Create Module-Info -> Click Finish.

15 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


2. Now Right Click On Project and Select Configure -> Convert to Maven Project.

Immediately It will show below details and click on Finish.

16 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


3. Now With Above Step, Java Project Supporting Maven functionalities. Created a default
pom.xml as well. Project Structure shown as below.

Now Open pox.xml file, add Spring Core JAR Dependencies to project and save it.

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>hello_spring</groupId>
<artifactId>hello_spring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.29</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.29</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>17</release>
</configuration>
</plugin>
</plugins>
</build>
</project>

17 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


After adding Dependencies, Maven downloads all Spring Core Jar files with internal
dependencies of jars at the same time configures those as part of Project automatically. As
a Developer we no need to configure of jars in this approach. Now we can See Downloaded
JAR files under Maven Dependencies Section as shown in below.

With This Our Java Project is Supporting Spring Core Module Functionalities. We can
Continue with Spring Core Module Functionalities.

NOTE: Below Steps are now common across our Spring Core Project created by either
Manual Jar files or Maven Configuration.

4. Now Create a java POJO Class in src inside package.

package com.naresh.hello;

public class Student {


private String studnetName;

public String getStudnetName() {


return studnetName;
}
public void setStudnetName(String studnetName) {
this.studnetName = studnetName;
}
}

5. Now create a xml file with any name in side our project root folder:

Ex: beans.xml

18 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


6. Now Inside beans.xml, and paste below XML Shema content to configure all our bean
classes.

<?xml version="1.0" encoding="UTF-8"?>


<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.xsd">

<!-- Configure Our Bean classes Here -->


</beans>

We can get above content from below link as well.


https://docs.spring.io/spring-framework/docs/4.2.x/spring-framework-reference/html/xsd-
configuration.html

7. Now configure our POJO class Student in side beans.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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="stu" class=" com.naresh.hello.Student"> </bean>


</beans>

From above Configuration, Points to be Noted:

• Every class will be configured with <bean> tag, we can call it as Bean class.
• The id attribute is a string that identifies the individual bean name in Spring IOC Container
i.e. similar to Object Name or Reference.
• The class attribute is fully qualified class name our class i.e. class name with package
name.

19 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


8. Now create a main method class for testing.

Here we are getting the object of Student class from the Spring IOC container using
the getBean() method of BeanFactory. Let's see the code

package com.naresh.hello;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class SpringCoreApp {


public static void main(String[] args) {

// BeanFactory Object is called as IOC Container.


BeanFactory factory = new

FileSystemXmlApplicationContext("D:\\workspaces\\naresit\\hello_spring\\beans.xml");

Student s = (Student) factory.getBean("stu");


System.out.println(s);
}
}

9. Now Execute Your Program : Run as Java Application.

In above example Student Object Created by Spring IOC container and we got it by using
getBean() method. If you observe, we are not written code for Student Object Creation i.e.
using new operator.

➢ We can create multiple Bean Objects for same Bean class with multiple bean
configurations in xml file.

20 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


<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.xsd">

<bean id="s1" class="com.naresh.hello.Student"> </bean>


<bean id="s2" class="com.naresh.hello.Student"> </bean>
</beans>

➢ Now In Main Application class, Get Second Object.

So we can provide multiple configurations and create multiple Bean Objects for a class.

Bean Overview:
A Spring IoC container manages one or more beans. These beans are created with the
configuration metadata that you supply to the container (for example, in the form of XML
<bean/> definitions). Every bean has one or more identifiers. These identifiers must be unique
within the container that hosts the bean. A bean usually has only one identifier. However, if
it requires more than one, the extra ones can be considered aliases. In XML-based
configuration metadata, you use the id attribute, the name attribute, or both to specify bean
identifiers. The id attribute lets you specify exactly one id.

Bean Naming Conventions:


The convention is to use the standard Java convention for instance field names when
naming beans. That is, bean names start with a lowercase letter and are camel-cased from
there. Examples of such names include accountManager, accountService, userDao,
loginController.

21 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Instantiating Beans:
A bean definition is essentially a recipe for creating one or more objects. The container
looks at the recipe for a named bean when asked and uses the configuration metadata
encapsulated by that bean definition to create (or acquire) an actual object.

If you use XML-based configuration metadata, you specify the type (or class) of object that is
to be instantiated in the class attribute of the <bean/> element. This class attribute (which,
internally, is a Class property on a BeanDefinition instance) is usually mandatory.

Types of Dependency Injection:

Dependency Injection (DI) is a design pattern that allows us to decouple the


dependencies of a class from the class itself. This makes the class more loosely coupled and
easier to test. In Spring, DI can be achieved through constructors, setters, or fields.

1. Setter Injection
2. Constructor Injection
3. Filed Injection

There are many benefits to using dependency injection in Spring. Some of the benefits
include:

• Loose coupling: Dependency injection makes the classes in our application loosely
coupled. This means that the classes are not tightly coupled to the specific
implementations of their dependencies. This makes the classes more reusable and easier
to test.
• Increased testability: Dependency injection makes the classes in our application more
testable. This is because we can inject mock implementations of dependencies into the
classes during testing. This allows us to test the classes in isolation, without having to
worry about the dependencies.
• Increased flexibility: Dependency injection makes our applications more flexible. This is
because we can change the implementations of dependencies without having to change
the classes that depend on them. This makes it easier to change the underlying
technologies in our applications.

Dependency injection is a powerful design pattern that can be used to improve the design
and testability of our Spring applications. By using dependency injection, we can make our
applications more loosely coupled, increase their testability, and improve their flexibility.

Setter Injection:

Setter injection is another way to inject dependencies in Spring. In this approach, we specify
the dependencies in the class setter methods. The Spring container will then create an
instance of the class and then call the setter methods to inject the dependencies.

22 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


The <property> sub element of <bean> is used for setter injection. Here we are going to inject

➢ primitive and String-based values


➢ Dependent object (contained object)
➢ Collection values etc.

Now Let’s take example for setter injection.

1. Create a class.

package com.naresh.first.core;

public class Student {

private String studentName;


private String studentId;
private String clgName;
public String getClgName() {
return clgName;
}
public void setClgName(String clgName) {
this.clgName = clgName;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public void printStudentDeatils() {
System.out.println("This is Student class");
}
public double getAvgOfMArks() {
return 456 / 6;
}
}

2. Configure bean in beans xml file :

<?xml version="1.0" encoding="UTF-8"?>

23 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


<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.xsd">

<bean id="s1" class="com.naresh.first.core.Student">


<property name="clgName" value="ABC College " />
<property name="studentName" value="Dilip Singh " />
<property name="studentId" value="100" />
</bean>
</beans>

From above configuration, <property> tag referring to setter injection i.e. injecting value to a
variable or property of Bean Student class.

<property> tag contains some attributes.

name: Name of the Property i.e. variable name of Bean class


value: Real/Actual value of Variable for injecting/storing

3. Now get the bean object from Spring Container and print properties values.

package com.naresh.first.core;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class SpringApp {


public static void main(String[] args) {

BeanFactory factory = new


FileSystemXmlApplicationContext("D:\\workspaces\\naresit\\spring_first\\beans.xm
l");

// Requesting Spring Container for Student Object


Student s1 = (Student) factory.getBean("s1");
System.out.println(s1.getStudentId());
System.out.println(s1.getStudentName());
System.out.println(s1.getClgName());
s1.printStudentDeatils();
System.out.println(s1.getAvgOfMArks());
}
}

24 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Output:
100
Dilip Singh
ABC College
This is Student class
76.0

Internal Workflow/Execution of Above Program.

1. From the Below Line execution, Spring will create Spring IOC container and Loads our
beans xml file in JVM memory and Creates Bean Objects inside Spring Container.

BeanFactory factory = new


FileSystemXmlApplicationContext("D:\\workspaces\\naresit\\spring_first\\beans.xml");

2. Now from below line, we are getting bean object of Student class configured with bean id
: s1

Student s1 = (Student) factory.getBean("s1");

3. Now we can use s1 object and call our method as usual.

Injecting primitive and String Data properties:


Now we are injecting/configuring primitive and String data type properties into Spring
Bean Object.

• Define a class, with different primitive datatypes and String properties.

package com.naresh.hello;

25 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


public class Student {

private String stuName;


private int studId;
private double avgOfMarks;
private short passedOutYear;
private boolean isSelected;

public String getStuName() {


return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getStudId() {
return studId;
}
public void setStudId(int studId) {
this.studId = studId;
}
public double getAvgOfMarks() {
return avgOfMarks;
}
public void setAvgOfMarks(double avgOfMarks) {
this.avgOfMarks = avgOfMarks;
}
public short getPassedOutYear() {
return passedOutYear;
}
public void setPassedOutYear(short passedOutYear) {
this.passedOutYear = passedOutYear;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
}

• Now configure above properties in spring beans xml file.

<bean id="studentOne" class="com.naresh.hello.Student">


<property name="stuName" value="Dilip"></property>
<property name="studId" value="101"></property>
<property name="avgOfMarks" value="99.88"></property>

26 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


<property name="passedOutYear" value="2022"></property>
<property name="isSelected" value="true"></property>
</bean>

• For primitive and String data type properties of bean class, we can use both name and
value attributes.
• Now let’s test values injected or not from above bean configuration.

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class SpringCoreApp {


public static void main(String[] args) {
ApplicationContext context = new
FileSystemXmlApplicationContext("D:\\workspaces\\naresit\\spring_notes\\beans.xml");
Student s1 = (Student) context.getBean("studentOne"); // get it from
container
System.out.println(s1.getStudId());
System.out.println(s1.getStuName());
System.out.println(s1.getPassedOutYear());
System.out.println(s1.getAvgOfMarks());
System.out.println(s1.isSelected());
}
}

Output:
101
Dilip
2022
99.88
True

Injecting Collection Data Types properties:

Now we are injecting/configuring Collection Data Types like List, Set and Map properties
into Spring Bean Object.

➢ For List data type property, Spring Provided <list> tag, sub tag of <property>.
<list>
<value> … </value>
<value>… </value>
<value> .. </value>
……………….
</list>
➢ For Set data type property, Spring Provided <list> tag, sub tag of <property>.
<set>

27 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


<value> … </value>
<value>… </value>
<value> .. </value>
……………….
</set>

➢ For Map data type property, Spring Provided <list> tag, sub tag of <property>.
<map>
<entry key="…" value="…" />
<entry key="…" value="…" />
<entry key="…" value="…" />
……………….
</map>

Created Bean class with List, Set and Map properties.

package com.naresh.hello;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class Student {

private String stuName;


private int studId;
private double avgOfMarks;
private short passedOutYear;
private boolean isSelected;
private List<String> emails;
private Set<String> mobileNumbers;
private Map<String, String> subMarks;

public List<String> getEmails() {


return emails;
}

public void setEmails(List<String> emails) {


this.emails = emails;
}

public Set<String> getMobileNumbers() {


return mobileNumbers;
}

28 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


public void setMobileNumbers(Set<String> mobileNumbers) {
this.mobileNumbers = mobileNumbers;
}

public Map<String, String> getSubMarks() {


return subMarks;
}

public void setSubMarks(Map<String, String> subMarks) {


this.subMarks = subMarks;
}

public String getStuName() {


return stuName;
}

public void setStuName(String stuName) {


this.stuName = stuName;
}

public int getStudId() {


return studId;
}

public void setStudId(int studId) {


this.studId = studId;
}

public double getAvgOfMarks() {


return avgOfMarks;
}

public void setAvgOfMarks(double avgOfMarks) {


this.avgOfMarks = avgOfMarks;
}

public short getPassedOutYear() {


return passedOutYear;
}

public void setPassedOutYear(short passedOutYear) {


this.passedOutYear = passedOutYear;
}

public boolean isSelected() {


return isSelected;

29 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}

public void setIsSelected(boolean isSelected) {


this.isSelected = isSelected;
}
}

Now configure in beans 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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="studentOne" class="com.naresh.hello.Student">


<property name="stuName" value="Dilip"></property>
<property name="studId" value="101"></property>
<property name="avgOfMarks" value="99.88"></property>
<property name="passedOutYear" value="2022"></property>
<property name="isSelected" value="true"></property>
<property name="emails">
<list>
<value>dilip@gmail.com</value>
<value>laxmi@gmail.com</value>
<value>dilip@gmail.com</value>
</list>
</property>
<property name="mobileNumbers">
<set>
<value>8826111377</value>
<value>8826111377</value>
<value>+1234567890</value>
</set>
</property>
<property name="subMarks">
<map>
<entry key="maths" value="88" />
<entry key="science" value="66" />
<entry key="english" value="44" />
</map>
</property>
</bean>
</beans>

• Now let’s test values injected or not from above bean configuration.

30 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


package com.naresh.hello;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class SpringCoreApp {


public static void main(String[] args) {
ApplicationContext context = new
FileSystemXmlApplicationContext("D:\\workspaces\\naresit\\spring_notes\\beans.xml");
Student s1 = (Student) context.getBean("studentOne"); // get it from
container
System.out.println(s1.getStudId());
System.out.println(s1.getStuName());
System.out.println(s1.getPassedOutYear());
System.out.println(s1.getAvgOfMarks());
System.out.println(s1.isSelected());
System.out.println(s1.getEmails()); // List Values
System.out.println(s1.getMobileNumbers()); // Set Values
System.out.println(s1.getSubMarks()); //Map values
}
}

Output:
101
Dilip
2022
99.88
true
[dilip@gmail.com, laxmi@gmail.com, dilip@gmail.com]
[8826111377, +1234567890]
{maths=88, science=66, english=44}

31 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Injecting Dependency’s of Other Bean Objects:

Now we are injecting/configuring other Bean Objects into another Spring Bean Object.

➢ Now Create a class : Address.java

package com.naresh.training.spring.core;

public class Address {

private String city;


private int pincode;
private String country;

public Address() {
System.out.println("Address instance/constructed ");
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getPincode() {
return pincode;
}
public void setPincode(int pincode) {
this.pincode = pincode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}

32 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ Now Create another class with Address Type Property: Student.java

package com.naresh.training.spring.core;

public class Student {

private String studentName;


private int studentId;
private Address address;

public Student() {
System.out.println("Student Constructor executed.");
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}

➢ Now Configure Address and Student Bean classes. Here, Address Bean Object is
dependency of Student object i.e. Address should be referred inside Student. To achive
this collaboration, Spring provided ref element/attribute.

ref attribute / <ref> element:

The ref element is the element inside a <property/> or <constructor-arg/> element. Here,
you set the value of the specified property of a bean to be a referenced to another bean (a
collaborator) managed by the container. Sometimes we can use ref attribute as part of
<property/> or <constructor-arg/>. We will provide bean Id for ref element which should be

33 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


injected into target Object. Please refer below, how to inject Bean Objects via ref element or
attribute.

➢ Configure Bean classes now inside beans.xml file.

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
<bean id="universityAddress"
class="com.naresh.training.spring.core.Address">
<property name="city" value="Bangloore"></property>
<property name="country" value="India"></property>
<property name="pincode" value="400066"></property>
</bean>
<!-- Student Bean Objects -->
<bean id="student1" class="com.naresh.training.spring.core.Student">
<property name="studentName" value="Dilip Singh"></property>
<property name="studentId" value="100"></property>
<property name="address" ref="universityAddress"></property>
</bean>
<bean id="student2" class="com.naresh.training.spring.core.Student">
<property name="studentName" value="Naresh"></property>
<property name="studentId" value="101"></property>
<property name="address">
<ref bean="universityAddress"/>
</property>
</bean>
</beans>

➢ Now let’s test values and references injected or not from above bean configuration.

package com.naresh.training.spring.core;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class SpringSetterInjectionDemo {

public static void main(String[] args) {

BeanFactory factory = new FileSystemXmlApplicationContext(


"D:\\Spring\\spring-
injection\\beans.xml");

System.out.println("************ Student1 Data *********");

34 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Student stu1 = (Student) factory.getBean("student1");
System.out.println(stu1.getStudentId());
System.out.println(stu1.getStudentName());
Address stu1Address = stu1.getAddress();
System.out.println(stu1Address.getCity());
System.out.println(stu1Address.getCountry());
System.out.println(stu1Address.getPincode());

System.out.println("************ Student2 Data *********");


Student stu2 = (Student) factory.getBean("student2");
System.out.println(stu2.getStudentId());
System.out.println(stu2.getStudentName());
System.out.println(stu2.getAddress().getCity());
System.out.println(stu2.getAddress().getCountry());
System.out.println(stu2.getAddress().getPincode());
}
}

Output:

Address instance/constructed
Student Contructor executed.
Student Contructor executed.
************ Student1 Data *********
100
Dilip Singh
Bangloore
India
400066
************ Student2 Data *********
101
Naresh
Bangloore
India
400066

From above output, same universityAddress bean Object is injected by Spring Container
internally inside both student1 and student2 Bean Objects.

Constructor Injection:

Constructor injection is a form of dependency injection where dependencies are


provided to a class through its constructor. It is a way to ensure that all required dependencies
are supplied when creating an object. In constructor injection, the class that requires
dependencies has one or more parameters in its constructor that represent the

35 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


dependencies. When an instance of the class is created, the dependencies are passed as
arguments to the constructor.

• Define AccountDetails Bean class.

package com.naresh.hello;

import java.util.Set;

public class AccountDetails {

private String name;


private double balance;
private Set<String> mobiles;
private Address customerAddress;

public AccountDetails(String name, double balance, Set<String> mobiles, Address


customerAddress) {
super();
this.name = name;
this.balance = balance;
this.mobiles = mobiles;
this.customerAddress = customerAddress;
}
public AccountDetails() {

}
public Address getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(Address customerAddress) {
this.customerAddress = customerAddress;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getBalance() {
return balance;
}

public void setBalance(double balance) {


this.balance = balance;
}
public Set<String> getMobiles() {

36 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


return mobiles;
}
public void setMobiles(Set<String> mobiles) {
this.mobiles = mobiles;
}
}

• Define Dependency Class Address.

package com.naresh.hello;

public class Address {

private int flatNo;


private String houseName;
private long mobile;

public int getFlatNo() {


return flatNo;
}
public void setFlatNo(int flatNo) {
this.flatNo = flatNo;
}
public String getHouseName() {
return houseName;
}
public void setHouseName(String houseName) {
this.houseName = houseName;
}
public long getMobile() {
return mobile;
}
public void setMobile(long mobile) {
this.mobile = mobile;
}

• Define Bean Configuration

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="

37 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="addr" class="com.naresh.hello.Address">


<property name="flatNo" value="333"></property>
<property name="houseName" value="Lotus Homes"></property>
<property name="mobile" value="91822222"></property>
</bean>

<bean id="accountDeatils"
class="com.naresh.hello.AccountDetails">
<constructor-arg name="name" value="Dilip" />
<constructor-arg name="balance" value="500.00" />
<constructor-arg name="mobiles">
<set>
<value>8826111377</value>
<value>8826111377</value>
<value>+91-88888888</value>
<value>+232388888888</value>
</set>
</constructor-arg>
<constructor-arg name="customerAddress" ref="addr" />
</bean>
</beans>

• Now Test Constructor Injection Beans and Configuration.

package com.naresh.hello;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class SpringCoreApp {


public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext(
"D:\\workspaces\\naresit\\spring_notes\\beans.xml");

AccountDetails details = (AccountDetails) context.getBean("accountDeatils");

System.out.println(details.getName());
System.out.println(details.getBalance());
System.out.println(details.getMobiles());
System.out.println(details.getCustomerAddress().getFlatNo());
System.out.println(details.getCustomerAddress().getHouseName());

38 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}

Output:
Dilip
500.0
[8826111377, +91-88888888, +232388888888]
333
Lotus Homes

Differences Between Setter and Constructor Injection.

Setter injection and constructor injection are two common approaches for
implementing dependency injection. Here are the key differences between them:

1. Dependency Resolution: In setter injection, dependencies are resolved and injected into
the target object using setter methods. In contrast, constructor injection resolves
dependencies by passing them as arguments to the constructor.

2. Timing of Injection: Setter injection can be performed after the object is created, allowing
for the possibility of injecting dependencies at a later stage. Constructor injection, on the
other hand, requires all dependencies to be provided at the time of object creation.

3. Flexibility: Setter injection provides more flexibility because dependencies can be changed
or modified after the object is instantiated. With constructor injection, dependencies are
typically immutable once the object is created.

4. Required Dependencies: In setter injection, dependencies may be optional, as they can be


set to null if not provided. Constructor injection requires all dependencies to be provided
during object creation, ensuring that the object is in a valid state from the beginning.

5. Readability and Discoverability: Constructor injection makes dependencies more explicit,


as they are declared as parameters in the constructor. This enhances the readability and
discoverability of the dependencies required by a class. Setter injection may result in a less
obvious indication of required dependencies, as they are set through individual setter
methods.

6. Testability: Constructor injection is generally favoured for unit testing because it allows for
easy mocking or substitution of dependencies. By providing dependencies through the
constructor, testing frameworks can easily inject mocks or stubs when creating objects for
testing. Setter injection can also be used for testing, but it may require additional setup or
manipulation of the object's state.

The choice between setter injection and constructor injection depends on the specific
requirements and design considerations of your application. In general, constructor injection
is recommended when dependencies are mandatory and should be set once during object
creation, while setter injection provides more flexibility and optional dependencies can be set
or changed after object instantiation.

39 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Bean Wiring in Spring:

Bean wiring, also known as bean configuration or bean wiring configuration, is the process of
defining the relationships and dependencies between beans in a container or application
context. In bean wiring, you specify how beans are connected to each other, how
dependencies are injected, and how the container should create and manage the beans. This
wiring process is typically done through configuration files or annotations.

package com.naresh.hello;

public class AreaDeatils {

private String street;


private String pincode;

public String getStreet() {


return street;
}

public void setStreet(String street) {


this.street = street;
}

public String getPincode() {


return pincode;
}

public void setPincode(String pincode) {


this.pincode = pincode;
}

Create Another Bean : Address

package com.naresh.hello;

public class Address {

private int flatNo;


private String houseName;
private long mobile;
private AreaDeatils area; // Dependency Of Another Class

public AreaDeatils getArea() {


return area;
}

40 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


public void setArea(AreaDeatils area) {
this.area = area;
}
public int getFlatNo() {
return flatNo;
}
public void setFlatNo(int flatNo) {
this.flatNo = flatNo;
}
public String getHouseName() {
return houseName;
}
public void setHouseName(String houseName) {
this.houseName = houseName;
}
public long getMobile() {
return mobile;
}
public void setMobile(long mobile) {
this.mobile = mobile;
}
}

• Create Another Bean : AccountDetails

package com.naresh.hello;

import java.util.Set;

public class AccountDetails {

private String name;


private double balance;
private Set<String> mobiles;
private Address customerAddress;
public AccountDetails(String name, double balance,
Set<String> mobiles, Address customerAddress) {
super();
this.name = name;
this.balance = balance;
this.mobiles = mobiles;
this.customerAddress = customerAddress;
}
public AccountDetails() {

}
public Address getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(Address customerAddress) {
this.customerAddress = customerAddress;

41 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getBalance() {
return balance;
}

public void setBalance(double balance) {


this.balance = balance;
}
public Set<String> getMobiles() {
return mobiles;
}
public void setMobiles(Set<String> mobiles) {
this.mobiles = mobiles;
}
}

➢ Beans Configuration in spring xml file. With “ref” attribute we are configuring bean
object each other internally.

<?xml version="1.0" encoding="UTF-8"?>

<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.xsd">

<bean id="areaDetails" class="com.naresh.hello.AreaDeatils">


<property name="street" value="Naresh It road"></property>
<property name="pincode" value="323232"></property>
</bean>

<bean id="addr" class="com.naresh.hello.Address">


<property name="flatNo" value="333"></property>
<property name="houseName" value="Lotus Homes"></property>
<property name="mobile" value="91822222"></property>
<property name="area" ref="areaDetails"></property>
</bean>

<bean id="accountDeatils" class="com.naresh.hello.AccountDetails">


<constructor-arg name="name" value="Dilip" />
<constructor-arg name="balance" value="500.00" />

42 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


<constructor-arg name="customerAddress" ref="addr" />
<constructor-arg name="mobiles">
<set>
<value>8826111377</value>
<value>8826111377</value>
<value>+91-88888888</value>
<value>+232388888888</value>
</set>
</constructor-arg>
</bean>
</beans>

AccountDetails
Address

AreaDeatils

Testing of Bean Configuration:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class SpringCoreApp {


public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext(
“D:\\workspaces\\naresit\\spring_notes\\beans.xml”);

AccountDetails details = (AccountDetails) context.getBean(“accountDeatils”);


System.out.println(details.getName());
System.out.println(details.getBalance());
System.out.println(details.getMobiles());
System.out.println(details.getCustomerAddress().getFlatNo());
System.out.println(details.getCustomerAddress().getArea().getPincode());

}
}

Output:

Dilip

43 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


500.0
[8826111377, +91-88888888, +232388888888]
333
323232
AutoWiring in Spring:

Autowiring feature of spring framework enables you to inject the objects dependency
implicitly. It internally uses setter or constructor injection. In Spring framework, the
“autowire” attribute is used in XML <bean> configuration files to enable automatic
dependency injection. It allows Spring to automatically wire dependencies between beans
without explicitly specifying them in the XML file.

To use autowiring in an XML bean configuration file, you need to define the
“autowire” attribute for a bean definition. The “autowire” attribute accepts different values
to determine how autowiring should be performed. There are many autowiring modes.

1. no : This is the default value. It means no autowiring will be performed, and you need to
explicitly specify dependencies using the appropriate XML configuration using property of
constructor tags.

2. byName : The byName mode injects the object dependency according to name of the
bean i.e. Bena ID. In such case, property name of class and bean ID must be same. It
internally calls setter method. If a match is found, the dependency will be injected.

3. byType: The byType mode injects the object dependency according to type i.e. Data Type
of Property. So property/variable name and bean name can be different int this case. It
internally calls setter method. If a match is found, the dependency will be injected. If
multiple beans are found, an exception will be thrown.

4. constructor: The constructor mode injects the dependency by calling the constructor of
the class. It calls the constructor having large number of parameters.

Here’s an examples of using the “autowire” attribute in an XML bean configuration file.

autowire=no:

For example, Define Product Class.

Public class Product {

private String 44roductid;


private String productName;

public Product() {
System.out.println(“Product Object Created by IOC”);

44 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}
public Product(String 45roductid, String productName) {
super();
this.productId = 45roductid;
this.productName = productName;
}
public String getProductId() {
return 45roductid;
}
public void setProductId(String 45roductid) {
this.productId = 45roductid;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
}

Now Define Class Order which is having dependency of Product Object i.e. product bean
object should be injected to Order.

Package com.flipkart.orders;

import com.flipkart.product.Product;

public class Order {

private String orderId;


private double orderValue;
private Product;

public Order() {
System.out.println(“Order Object Created by IOC”);
}

public Order(String orderId, double orderValue, Product product) {


super();
this.orderId = orderId;
this.orderValue = orderValue;
this.product = product;
}

public String getOrderId() {


return orderId;
}

45 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


public void setOrderId(String orderId) {
this.orderId = orderId;
}

public double getOrderValue() {


return orderValue;
}

public void setOrderValue(double orderValue) {


this.orderValue = orderValue;
}

public Product getProduct() {


return product;
}

public void setProduct(Product product) {


this.product = product;
}
}

Now let’s configure both Product and Order in side beans xml file.

<beans>

<bean id=”product” class=”com.flipkart.product.Product”>


<property name=”46roductid” value=”101”></property>
<property name=”productName” value=”Lenevo Laptop”></property>
</bean>
<bean id=”order” class=”com.flipkart.orders.Order” autowire=”no”>
<property name=”orderId” value=”order1234”></property>
<property name=”orderValue” value=”33000.00”></property>
</bean>

</beans>

Now Try to request Object of Order from IOC Container.

Package com.flipkart.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import com.flipkart.orders.Order;
import com.flipkart.orders.OrdersManagement;
import com.flipkart.product.Product;

46 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


public class AutowiringDemo {
public static void main(String[] args) {
// IOC Container
ApplicationContext context = new FileSystemXmlApplicationContext(
“D:\\workspaces\\naresit\\bean-wiring\\beans.xml”);
Order = (Order) context.getBean(“order”);
System.out.println(
order.getProduct() // Product Object
.getProductId() // Product object : Getting product Id
);
}
}
Now we got an exception, as shown below.

Product Object Created by IOC


Order Object Created by IOC
Exception in thread “main” java.lang.NullPointerException:
Cannot invoke “com.flipkart.product.Product.getProductId()”
because the return value of
“com.flipkart.orders.Order.getProduct()” is null at
com.flipkart.main.AutowiringDemo.main(AutowiringDemo.java:22)

Means, Product and Order Object created by Spring but not injected product bean object
automatically in side Order Object by IOC Container with setter injection internally. Because
we used autowire mode as no. By Default autowire value is “no” i.e. Even if we are not given
autowire attribute internally Spring Considers it as autowire=”no”.

autowire=”byName”:

Now configure autowire=”byName” in side beans xml file for order Bean
configuration, because internally Product bean object should be injected to Order Bean
Object.In this autowire mode, We are expecting dependency injection of objects by Spring
instead of we are writing bean wiring with either using <property> and <constructor-arg> tags
by using ref attribute. Means, eliminating logic of reference configurations.

As per autowire=”byName”, Spring internally checks for a dependency bean objects which is
matched to property names of Object. As per our example, Product is dependency for Order
class.
Product class Bean ID = Property Name of Order class

47 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Internally Spring comparing as shown in above and injected product bean object to Order
object.

Beans Configuration:

<beans>
<bean id="product" class="com.flipkart.product.Product">
<property name="productId" value="101"></property>
<property name="productName" value="Lenevo Laptop"></property>
</bean>

<bean id="order" class="com.flipkart.orders.Order" autowire="byName">


<property name="orderId" value="order1234"></property>
<property name="orderValue" value="33000.00"></property>
</bean>
</beans>

Now test our application.

48 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


So Internally Spring injected Product object by name of bean and property name of Order
class.

Question: If property name and Bean ID are different, then Spring will not inject Product
object inside Order Object. Now I made bean id as prod for Product class.

Test Our application and check Spring injected Product object or not inside Order.

49 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Product Object Created by IOC
Order Object Created by IOC
Exception in thread "main" java.lang.NullPointerException:
Cannot invoke "com.flipkart.product.Product.getProductId()"
because the return value of
"com.flipkart.orders.Order.getProduct()" is null at
com.flipkart.main.AutowiringDemo.main(AutowiringDemo.java:19)

autowire=”byType”:

Now configure autowire=”byType” in side beans xml file for Order Bean configuration,
because internally Product bean object should be injected to Order Bean Object. In this
autowire mode, We are expecting dependency injected by Spring instead of we are writing
bean wiring with either using <property> and <constructor-arg> tags by using ref attribute.
Means, eliminating logic of reference configurations.

As per autowire=”byType”, Spring internally checks for a dependency bean objects, which
are matched with Data Type of property and then that bean object will be injected. In this
case Bean ID and Property Names may be different. As per our example, Product is
dependency for Order class.

Bean Data Type i.e. class Name = Data type of property of Order class

Beans Configuration:

<beans>
<bean id="prod" class="com.flipkart.product.Product">
<property name="productId" value="101"></property>
<property name="productName" value="Lenevo Laptop"></property>
</bean>
<bean id="order" class="com.flipkart.orders.Order" autowire="byType">

50 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


<property name="orderId" value="order1234"></property>
<property name="orderValue" value="33000.00"></property>
</bean>
</beans>

Test Our Application Now: Injected Successfully, because only One Product Object available.

Question: If Product Bean configured more than one time inside beans configuration, then
which Product Bean Object will be injected in side Order ?

<bean id="prod" class="com.flipkart.product.Product">


<property name="productId" value="101"></property>
<property name="productName" value="Lenevo Laptop"></property>
</bean>
<bean id="prod2" class="com.flipkart.product.Product">
<property name="productId" value="101"></property>
<property name="productName" value="Lenevo Laptop"></property>
</bean>

51 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Test Our Application: We will get Exception while trying to inject Product Object because of
ambiguity between 2 Objects.

Product Object Created by IOC


Product Object Created by IOC
Order Object Created by IOC
Jul 11, 2023 1:56:23 PM org.springframework.context.support.AbstractApplicationContext
refresh
WARNING: Exception encountered during context initialization - cancelling refresh
attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'order' defined in file [D:\workspaces\naresit\bean-
wiring\beans.xml]: Unsatisfied dependency expressed through bean property 'product';
nested exception is
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying
bean of type 'com.flipkart.product.Product' available: expected single matching bean but
found 2: prod,prod2
Exception in thread "main"
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean
with name 'order' defined in file [D:\workspaces\naresit\bean-wiring\beans.xml]:
Unsatisfied dependency expressed through bean property 'product'; nested exception is
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying
bean of type 'com.flipkart.product.Product' available: expected single matching bean but
found 2: prod,prod2

autowire=” constructor”:
Now configure autowire=”constructor” in side beans xml file for Order Bean
configuration, because internally Product bean object should be injected to Order Bean
Object. In this autowire mode, We are expecting dependency injected by Spring instead of we
are writing bean wiring with either using <property> or <constructor-arg> tags by using ref
attribute. Means, eliminating logic of reference configurations.

52 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


As per autowire=”constructor”, Spring internally checks for a dependency bean objects,
which are matched with constructor argument of same data type and then that bean object
will be injected. Means, constructor autowire mode works with constructor injection not
setter injection. In this case, injected Bean Type and Constructor Property Name should be
same.

As per our example, Product is dependency for Order and Order class defined a constructor
with parameter contains Product type.

Beans Configuration:

<bean id="prod" class="com.flipkart.product.Product">


<property name="productId" value="101"></property>
<property name="productName" value="Lenevo Laptop"></property>
</bean>
<bean id="order" class="com.flipkart.orders.Order" autowire="constructor">
<constructor-arg index="0" value="order1234"></constructor-arg>
<constructor-arg index="1" value="33000"></constructor-arg>
</bean>

Test Our Application: Now Product Object Injected via Constructor.

53 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Question: If Product Bean configured more than one time inside beans configuration, then
which Product Bean Object will be injected in side Order ?

when autowire =constructor, spring internally checks out of multiple bean ids dependency
object which is matching with property name of Order class. If matching found then that
specific bean object will be injected. If not found then we will get ambiguity exception as
following.

As per our below configuration, both bean ids of Product are not matching with Order class
property name of Product type.

<bean id="prod" class="com.flipkart.product.Product">


<property name="productId" value="101"></property>
<property name="productName" value="Lenevo Laptop"></property>
</bean>
<bean id="prod2" class="com.flipkart.product.Product">
<property name="productId" value="101"></property>
<property name="productName" value="Lenevo Laptop"></property>
</bean>

54 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Test Our Application: We will get Exception while trying to inject Product Object because of
ambiguity between 2 Objects.

Product Object Created by IOC


Product Object Created by IOC
Jul 11, 2023 1:56:23 PM org.springframework.context.support.AbstractApplicationContext
refresh
WARNING: Exception encountered during context initialization - cancelling refresh
attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'order' defined in file [D:\workspaces\naresit\bean-
wiring\beans.xml]: Unsatisfied dependency expressed through bean property 'product';
nested exception is
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying
bean of type 'com.flipkart.product.Product' available: expected single matching bean but
found 2: prod,prod2
Exception in thread "main"
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean
with name 'order' defined in file [D:\workspaces\naresit\bean-wiring\beans.xml]:
Unsatisfied dependency expressed through bean property 'product'; nested exception is
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying
bean of type 'com.flipkart.product.Product' available: expected single matching bean but
found 2: prod,prod2

Now if we configure one bean object of Product class with bean id which is matching with
property name of Order class. Then that Specific Object will be injected. From following
configuration Product object of bean id “product” will be injected.

<bean id="product" class="com.flipkart.product.Product">


<property name="productId" value="101"></property>
<property name="productName" value="Lenevo Laptop"></property>
</bean>
<bean id="prod2" class="com.flipkart.product.Product">

55 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


<property name="productId" value="101"></property>
<property name="productName" value="Lenevo Laptop"></property>
</bean>

Test Our Application :

Advantage of Autowiring:
• It requires less code because we don’t need to write the code to inject the dependency
explicitly.

Disadvantage of Autowiring:
• No control of the programmer.
• It can’t be used for primitive and string values.

Bean Scopes in Spring:


When you start a Spring application, the Spring Framework creates beans for you.
These Spring beans can be application beans that you have defined or beans that are part of
the framework. When the Spring Framework creates a bean, it associates a scope with the
bean. A scope defines the life cycle and visibility of that bean within runtime application
context which the bean instance is available.

The Latest Spring Framework supports 5 scopes, last four are available only if you use Web
aware of ApplicationContext i.e. inside Web applications.

1. singleton

56 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


2. prototype
3. request
4. session
5. application
6. websokcet

Defining Scope of beans syntax:

In XML configuration, we will use an attribute “scope”, inside <bean> tag as shown below.

<!-- A bean definition with singleton scope -->


<bean id = "..." class = "..." scope = "singleton">
<!-- collaborators and configuration for this bean go here -->
</bean>

singleton:

This is default scope of a bean configuration i.e. even if we are not provided scope
attribute as part of any bean configuration, then spring container internally consideres as
scope=”singleton”.

If Bean scope=singleton, then Spring Container creates only one object in side Spring
container overall application level and Spring Container returns same instance reference
always for every IOC container call i.e. getBean().

<bean id="productOne" class="com.flipkart.product.Product" scope="singleton">

Above Is equal to following because default is scope="singleton"

<bean id="productOne" class="com.flipkart.product.Product">

Now create Bean class and call IOC container many time with same bean ID.

Product.java

public class Product {


private String productId;
private String productName;

public Product() {
System.out.println("Product Object Created by IOC");
}

//setters and getters methods


}

57 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Now configure above class in side beans xml file.

<bean id="product" class="com.flipkart.product.Product" scope="singleton">


<property name="productId" value="101"></property>
<property name="productName" value="Lenevo Laptop"></property>
</bean>
Now call Get Bean from IOC Container for Product Bean Object. In Below, we are calling IOC
container 3 times.

public class BeanScopesDemo {


public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext(
"D:\\workspaces\\naresit\\bean-wiring\\beans.xml");

// 1. Requesting/Calling IOC Container for Product Object


Product p1 = (Product) context.getBean("product");
System.out.println(p1.getProductId());
System.out.println(p1);

// 2. Requesting/Calling IOC Container for Product Object


Product p2 = (Product) context.getBean("product");
System.out.println(p2.getProductId());
System.out.println(p2);

// 3. Requesting/Calling IOC Container for Product Object


Product p3 = (Product) context.getBean("product");
System.out.println(p3.getProductId());
System.out.println(p3);
}
}

Output:

58 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


From above output, Spring created only one Object and same passed for every new IOC
container call getBean() of that bean id. Means, Singleton Object created for bean ID
product in IOC container.

NOTE: If we created another bean id configuration for same class, then previous configuration
behaviour will not applicable to current configuration i.e. every individual bean configuration
or Bean Object having it’s own behaviour and functionality in Spring Framework.

Create one more bean configuration of Product.


<bean id="product" class="com.flipkart.product.Product" scope="singleton">
<property name="productId" value="101"></property>
<property name="productName" value="Lenevo Laptop"></property>
</bean>
<bean id="productTwo" class="com.flipkart.product.Product">
<property name="productId" value="102"></property>
<property name="productName" value="HP Laptop"></property>
</bean>

Testing: In below we are requesting 2 different bean objects of Product.

public class BeanScopesDemo {


public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext(
"D:\\workspaces\\naresit\\bean-wiring\\beans.xml");

// 1. Requesting/Calling IOC Container for Product Object


Product p1 = (Product) context.getBean("product");
System.out.println(p1.getProductId());
System.out.println(p1);
// 2. Requesting/Calling IOC Container for Product Object
Product p2 = (Product) context.getBean("product");
System.out.println(p2.getProductId());
System.out.println(p2);
// 3. Requesting/Calling IOC Container for Product Object
Product p3 = (Product) context.getBean("productTwo");
System.out.println(p3.getProductId());
System.out.println(p3);
// 4. Requesting/Calling IOC Container for Product Object
Product p4 = (Product) context.getBean("productTwo");
System.out.println(p4.getProductId());
System.out.println(p4);
}
}
Output:

59 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


For 2 Bean configurations of Product class, 2 individual Singleton Bean Objects created.
prototype:
If Bean scope defined as “prototype”, a new instance of the bean is created every time
it is requested from the container. It is not cached, so each request/call to IOC container for
the bean will return in a new instance.

Bean class: Product.java

public class Product {

private String productId;


private String productName;

public Product() {
System.out.println("Product Object Created by IOC");
}

//setters and getters


}

XML Bean configuration:

<bean id="product" class="com.flipkart.product.Product" scope="prototype">


<property name="productId" value="101"></property>
<property name="productName" value="Lenevo Laptop"></property>
</bean>

Testing :

60 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Now Spring Container created and returned every time new Bean Object for every
Container call getBean() for same bean ID.
request:
When we apply scope as request, then for every new HTTP request Spring will crates new
instance of configured bean. Only valid in the context of a web-aware Spring
ApplicationContext i.e. in web/MVC applications.

session:
When we apply scope as session, then for every new HTTP session creation in server side
Spring will crates new instance of configured bean. Only valid in the context of a web-aware
Spring ApplicationContext i.e. in web/MVC applications.

application:
Once you have defined the application-scoped bean, Spring will create a single instance of the
bean per web application context. Any requests for this bean within the same web application
will receive the same instance.

It's important to note that the application scope is specific to web applications and relies on
the lifecycle of the web application context. Each web application running in a container will
have its own instance of the application-scoped bean.

You can use application-scoped beans to store and share application-wide state or resources
that need to be accessible across multiple components within the same web application.

websocket:
This is used as part of socket programming. We can’t use in our Servlet based MVC
application level.

61 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Java/Annotation Based Beans Configuration:
So far we have seen how to configure Spring beans using XML configuration file. Java-
based configuration option enables you to write most of your Spring configuration without
XML but with the help of annotations.

@Configuration & @Bean Annotations:


@Configuration:

In Java Spring, the @Configuration annotation is used to indicate that this class is a
configuration class of Beans. A configuration class is responsible for defining beans and their
dependencies in the Spring application context. Beans are objects that are managed by the
Spring IOC container. Annotating a class with the @Configuration indicates that the class can
be used by the Spring IOC container as a source of bean definitions.

Create a Java class and annotate it with @Configuration. This class will serve as our
configuration class.

@Bean:

In Spring, the @Bean annotation is used to declare a method as a bean definition


method within a configuration class. The @Bean annotation tells Spring that a method
annotated with @Bean will return an object that should be registered as a bean in the Spring
application context. The method annotated with @Bean is responsible for creating and
configuring an instance of a bean that will be managed by the Spring IoC (Inversion of Control)
container.

62 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Now Create a Project and add below jar files to support Spring Annotations of Core Module.

NOTE: Added one extra jar file comparing with previous project setup. Because internally
Spring using AOP functionalities to process annotations and we can ignore it.

➢ Now Create a Bean class : UserDetails

package com.amazon.users;

public class UserDetails {

private String firstName;


private String lastName;
private String emailId;
private String password;
private long mobile;

//setters and getters


}

Now Create a Beans Configuration class. i.e. Class Marked with an annotation
@Configuration. In side this configuration class, we will define multiple bean configurations
with @Bean annotation methods.

Configuration class would be as follows:

package com.amazon.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

63 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


import com.amazon.users.UserDetails;

@Configuration
public class BeansConfiguration {

@Bean("userDetails")
UserDetails getUserDetails() {

return new UserDetails();

}
}

The above code will be equivalent to the following XML bean configuration −

<beans>
<bean id = " userDetails " class = " com.amazon.users.UserDetails " />
</beans>

Here, the method is annotated with @Bean("userDetails") works as bean ID is userDetails


and Spring creates bean object with that bean ID and returns the same bean object when we
call getBean(). Your configuration class can have a declaration for more than one @Bean.
Once your configuration classes are defined, you can load and provide them to Spring
container using AnnotationConfigApplicationContext as follows .

package com.amazon;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.amazon.config.BeansConfiguration;
import com.amazon.users.UserDetails;

public class SpringBeanMainApp {

public static void main(String[] args) {


AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(BeansConfiguration.class);

UserDetails user = (UserDetails) context.getBean("userDetails");


System.out.println(user);

context.close();
}

64 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Output: Prints hash code of Object

com.amazon.users.UserDetails@34bde49d

From above code :

AnnotationConfigApplicationContext:

AnnotationConfigApplicationContext is a class provided by the Spring Framework


that serves as an implementation of the ApplicationContext interface. It is used to create an
application context container by reading Java-based configuration metadata. In Spring, there
are multiple ways to configure the application context, such as XML-based configuration or
Java-based configuration using annotations.
AnnotationConfigApplicationContext is specifically used for Java-based
configuration. It allows you to bootstrap the Spring container by specifying one or more Spring
configuration classes that contain @Configuration annotations.
We will provide configuration classes as Constructor parameters of
AnnotationConfigApplicationContext or spring provided register() method also. We will
have example here after.

➢ context.getBean(), Returns an instance, which may be shared or independent, of the


specified bean.
➢ context.close(), Close this application context, destroying all beans in its bean factory.
Multiple Configuration Classes and Beans:

Now we can configure multiple bean classes inside multiple configuration classes as well
as Same bean with multiple bean id’s.

Now I am crating one more Bean class in above application.

package com.amazon.products;

public class ProductDetails {

private String pname;


private double price;

public String getPname() {


return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {

65 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


this.price = price;
}
}

Configuring above POJO class as Bean class inside Beans Configuration class.

package com.amazon.config;

import org.springframework.context.annotation.Bean;
import com.amazon.products.ProductDetails;

public class BeansConfigurationTwo {

@Bean("productDetails")
ProductDetails productDetails() {
return new ProductDetails();
}
}

Testing Bean Object Created or not. Below Code loading Two Configuration classes.

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.amazon.config.BeansConfiguration;
import com.amazon.config.BeansConfigurationTwo;
import com.amazon.products.ProductDetails;
import com.amazon.users.UserDetails;
public class SpringBeanMainApp {

public static void main(String[] args) {

AnnotationConfigApplicationContext context = new


AnnotationConfigApplicationContext();

context.register(BeansConfiguration.class); //UserDetails Bean Config.


context.register(BeansConfigurationTwo.class); //ProductDetails Bean Config.

context.refresh();

UserDetails user = (UserDetails) context.getBean("userDetails");


System.out.println(user);

ProductDetails product = (ProductDetails) context.getBean("productDetails");


System.out.println(product);

context.close();
}

66 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}

Now Crate multiple Bean Configurations for same Bean class.

➢ Inside Configuration class: Two Bean configurations for ProductDetails Bean class.

import org.springframework.context.annotation.Bean;
import com.amazon.products.ProductDetails;

public class BeansConfigurationTwo {

@Bean("productDetails")
ProductDetails productDetails() {
return new ProductDetails();
}
@Bean("productDetailsTwo")
ProductDetails productTwoDetails() {
return new ProductDetails();
}
}

➢ Now get Both bean Objects of ProductDeatils.

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.amazon.config.BeansConfiguration;
import com.amazon.config.BeansConfigurationTwo;
import com.amazon.products.ProductDetails;
import com.amazon.users.UserDetails;

public class SpringBeanMainApp {

public static void main(String[] args) {

AnnotationConfigApplicationContext context = new


AnnotationConfigApplicationContext();

context.register(BeansConfiguration.class);
context.register(BeansConfigurationTwo.class);
context.refresh();

UserDetails user = (UserDetails) context.getBean("userDetails");


System.out.println(user);

ProductDetails product = (ProductDetails) context.getBean("productDetails");


System.out.println(product);

67 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


ProductDetails productTwo = (ProductDetails)
context.getBean("productDetailsTwo");
System.out.println(productTwo);

context.close();
}

}
Output:
com.amazon.users.UserDetails@7d3e8655
com.amazon.products.ProductDetails@7dfb0c0f
com.amazon.products.ProductDetails@626abbd0

From above Output Two ProductDetails bean objects created by Spring Container.

Above Project Files Structure:

@Component Annotation :

Before we can understand the value of @Component, we first need to understand a


little bit about the Spring ApplicationContext.
Spring ApplicationContext is where Spring holds instances of objects that it has identified to
be managed and distributed automatically. These are called beans. Some of Spring's main
features are bean management and dependency injection. Using the Inversion of Control
principle, Spring collects bean instances from our application and uses them at the
appropriate time. We can show bean dependencies to Spring without handling the setup and
instantiation of those objects.

68 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


However, the base/regular spring bean definitions are explicitly defined in the XML
file or configured in configuration class with @Bean, while the annotations drive only the
dependency injection. This section describes an option for implicitly/internally detecting the
candidate components by scanning the classpath. Components are classes that match against
a filter criteria and have a corresponding bean definition registered with the container. This
removes the need to use XML to perform bean registration. Instead, you can use annotations
(for example, @Component) to select which classes have bean definitions registered with the
container.

We should take advantage of Spring's automatic bean detection by using stereotype


annotations in our classes.

@Component: This annotation that allows Spring to detect our custom beans automatically.
In other words, without having to write any explicit code, Spring will:

• Scan our application for classes annotated with @Component


• Instantiate them and inject any specified dependencies into them
• Inject them wherever needed

We have other more specialized stereotype annotations like @Controller, @Service and
@Repository to serve this functionality derived , we will discuss then in MVC module level.

Define Spring Components :

1. Create a java Class and provide an annotation @Component at class level.

package com.tek.teacher;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
public class Product {

private String pname;


private double price;

public Product(){
System.out.println(“Product Object Created.”);
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public double getPrice() {

69 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


return price;
}
public void setPrice(double price) {
this.price = price;
}
}

Now Test in Main Class.

import
org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringComponentDemo {

public static void main(String[] args) {


AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext();

context.scan("com.tek. teacher");

context.refresh();

Product details = (Product) context.getBean(Product.class);


System.out.println(details);

}
}

From Above program, context.scan() method, Perform a scan for @Component classes to
instantiate Bean Objects within the specified base packages. We can pass many package
names wherever we have @Componet Classes. Note that, scan(basePackages) method will
scans @Confguraion classes as well from specified package names. Note that refresh() must
be called in order for the context to fully process the new classes.

Spring Provided One more way which used mostly in Real time applications is using
@ComponentScan annotation. To enable auto detection of Spring components, we shou use
another annotation @ComponentScan.

@ComponentScan:

Before we rely entirely on @Component, we must understand that it's only a plain
annotation. The annotation serves the purpose of differentiating beans from other objects,
such as domain objects. However, Spring uses the @ComponentScan annotation to gather all
component into its ApplicationContext.

70 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@ComponentScan annotation is used to specify packages for spring to scan for
annotated components. Spring needs to know which packages contain beans, otherwise you
would have to register each bean individually. Hence @ComponentScan annotation is a
supporting annotation for @Configuration annotation. Spring instantiate Bean Objects of
components from specified packages for those classes annotated with @Component.
So create a beans configuration class i.e. @Configuration annotated class and provide
@ComponentScan with base package name.
Ex: When we have to scan multiple packages we can pass all package names as String array
with attribute basePackages.
@ComponentScan(basePackages =
{"com.hello.spring.*","com.hello.spring.boot.*"})

Or If only one base package and it’s sub packages should be scanned, then we can directly
pass package name.
@ComponentScan("com.hello.spring.*")

Test our component class:

➢ Create A @Configuration class with @ComponentScan annotation.

@Configuration
// making sure scanning all packages starts with
com.tek.teacher
@ComponentScan("com.tek.teacher.*")
public class BeansConfiguration {

➢ Now Load/pass above configuration class to Application Context i.e. Spring Container.

package com.tek.teacher;

import
org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringComponentDemo {

public static void main(String[] args) {


AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext();

context.register(BeansConfiguration.class);
context.refresh();

Product details = (Product) context.getBean(Product.class);

71 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


System.out.println(details);

➢ Now Run your Main class application.

Output:
ProductDetails [pname=null, price=0.0]

From above, Spring Container detected @Component classes from all packages and
instantiated as Bean Objects.

Now Add One More @Component class:

package com.tek.teacher;

import org.springframework.stereotype.Component;

@Component
public class UserDetails {

private String firstName;


private String lastName;
private String emailId;
private String password;
private long mobile;

public UserDetails(){
System.out.println(“UserDetails Object Created”);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailId() {
return emailId;
}

72 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public long getMobile() {
return mobile;
}
public void setMobile(long mobile) {
this.mobile = mobile;
}
}

➢ Now get UserDetails from Spring Container and Test/Run our Main class.

package com.tek.teacher;

import
org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringComponentDemo {

public static void main(String[] args) {


AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext();

context.register(BeansConfiguration.class);
context.refresh();

//UserDetails Component
UserDetails userDetails = context.getBean(UserDetails.class);
System.out.println(userDetails);
}
}

Output: com.tek.teacher.UserDetails@5e17553a

NOTE: In Above Logic, used getBean(Class<UserDetails> requiredType), Return the bean


instance that uniquely matches the given object type, if any. Means, when we are not
configured any component name or don’t want to pass bean name from getBean() method.

73 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


We can use any of overloaded method getBean() to get Bean Object as per our requirement
or functionality demanding.

Can we Pass Bean Scope to @Component Classes?

Yes, Similar to @Bean annotation level however we are assigning scope type , we can pass in
same way with @Component class level because Component is nothing but Bean finally.

Ex : From above example, requesting another Bean Object of type UserDetails without
configuring scope at component class level.

package com.tek.teacher;

import
org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringComponentDemo {

public static void main(String[] args) {


AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext();
context.register(BeansConfiguration.class);
context.refresh();

// UserDetails Component
UserDetails userDetails = context.getBean(UserDetails.class);
System.out.println(userDetails);

UserDetails userTwo = context.getBean(UserDetails.class);


System.out.println(userTwo);

}
}

Output:
com.tek.teacher.UserDetails@5e17553a
com.tek.teacher.UserDetails@5e17553a

So we can say by default component classes are instantiated as singleton bean object, when
there is no scope defined. Means, Internally Spring Container considering as singleton scope.

Question : Can we create @Bean configurations for @Component class?

Yes, We can create Bean Configurations in side Spring Configuration classes. With That Bean
ID, we can request from Application Context, as usual.

74 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Inside Configuration Class:

package com.tek.teacher;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.tek.*")
public class BeansConfiguration {

@Bean("user")
UserDetails getUserDetails() {
return new UserDetails();
}

Testing from Main Class:

package com.tek.teacher;

import
org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringComponentDemo {

public static void main(String[] args) {


AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext();
context.register(BeansConfiguration.class);
context.refresh();

// UserDetails Component
UserDetails userThree = (UserDetails) context.getBean("user");
System.out.println(userThree);

}
}

Output:
com.tek.teacher.UserDetails@3eb91815

Question : How to pass default values to @Component class properties?

75 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


We can pass/initialize default values to a component class instance with @Bean configuration
implementation inside Spring Configuration classes.

Inside Configuration Class:

package com.tek.teacher;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.tek.*")
public class BeansConfiguration {

@Bean("user")
UserDetails getUserDetails() {
UserDetails user = new UserDetails();
user.setEmailId("dilip@gmail.com");
user.setMobile(8826111377l);
return user;
}
}
Main App:

package com.tek.teacher;

import
org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringComponentDemo {

public static void main(String[] args) {


AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext();

context.register(BeansConfiguration.class);
context.refresh();

// UserDetails Component
UserDetails userThree = (UserDetails) context.getBean("user");
System.out.println(userThree.getEmailId());
System.out.println(userThree.getMobile());

}
}
Output:

76 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


dilip@gmail.com
8826111377

Defining Scope of beans with Annotations:

In XML configuration, we will use an attribute “scope”, inside <bean> tag as shown below.

<!-- A bean definition with singleton scope -->


<bean id = "..." class = "..." scope = "singleton">
<!-- collaborators and configuration for this bean go here -->
</bean>
Annotation Based Scope Configuration:

We will use @Scope annotation will be used to define scope type.

@Scope: A bean’s scope is set using the @Scope annotation. By default, the Spring
framework creates exactly one instance for each bean declared in the IoC container. This
instance is shared in the scope of the entire IoC container and is returned for all subsequent
getBean() calls and bean references.

Example: Create a bean class and configure with Spring Container.

Bean Class: ProductDetails.java

package com.amazon.products;

public class ProductDetails {


private String pname;
private double price;
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public void printProductDetails() {
System.out.println("Product Details Are : .....");
}

77 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Now Inside Configuration class, Define Bean Creation and Configure scope value.

Singleton Scope:

A single Bean object instance created and returns same Bean instance for each Spring IoC
container call i.e. getBean(). In side Configuration class, scope value defined as singleton.

NOTE: If we are not defined any scope value for any Bean Configuration, then Spring
Container by default considers scope as singleton.

package com.amazon.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import com.amazon.products.ProductDetails;

@Configuration
public class BeansConfigurationThree {

@Scope("singleton")
@Bean("productDetails")
ProductDetails getProductDetails() {
return new ProductDetails();
}

➢ Now Test Bean ProdcutDetails Object is singleton or not. Request multiple times
ProductDetails Object from Spring Container by passing bean id productDetails.

package com.amazon;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.amazon.config.BeansConfigurationThree;
import com.amazon.products.ProductDetails;

public class SpringBeanScopeTest {

public static void main(String[] args) {


AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext();

context.register(BeansConfigurationThree.class);
context.refresh();

78 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


ProductDetails productOne = (ProductDetails)
context.getBean("productDetails");
System.out.println(productOne);

ProductDetails productTwo = (ProductDetails)


context.getBean("productDetails");
System.out.println(productTwo);

context.close();

}
}
Output:
com.amazon.products.ProductDetails@58e1d9d
com.amazon.products.ProductDetails@58e1d9d

From above output, we can see same hash code printed for both getBean() calls on Spring
Container. Means, Container created singleton instance for bean id “productDetails”.

Prototype Scope: In side Configuration class, scope value defined as prototype.

package com.amazon.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import com.amazon.products.ProductDetails;

@Configuration
public class BeansConfigurationThree {

@Scope("singleton")
@Bean("productDetails")
ProductDetails getProductDetails() {
return new ProductDetails();
}

@Scope("prototype")
@Bean("productTwoDetails")
ProductDetails getProductTwoDetails() {
return new ProductDetails();
}

79 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ Now Test Bean ProdcutDetails Object is prototype or not. Request multiple times
ProductDetails Object from Spring Container by passing bean id productTwoDetails.

import
org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.amazon.config.BeansConfigurationThree;
import com.amazon.products.ProductDetails;

public class SpringBeanScopeTest {

public static void main(String[] args) {

AnnotationConfigApplicationContext context = new


AnnotationConfigApplicationContext();

context.register(BeansConfigurationThree.class);
context.refresh();

//Prototype Beans:
ProductDetails productThree = (ProductDetails)
context.getBean("productTwoDetails");
System.out.println(productThree);

ProductDetails productFour = (ProductDetails)


context.getBean("productTwoDetails");
System.out.println(productFour);

context.close();

Output:
com.amazon.products.ProductDetails@12591ac8
com.amazon.products.ProductDetails@5a7fe64f

From above output, we can see different hash codes printed for both getBean() calls on Spring
Container. Means, Container created new instance every time when we requested for
instance of bean id “productTwoDetails”.

Scope of @Component classes:


If we want to define scope of with component classes and Objects externally, then we will use
same @Scope at class level of component class similar to @Bean method level in previous
examples.

80 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


If we are not passed any scope value via @Scope annotation to a component class, then
Component Bean Object will be created as singleton as usually.

Now for UserDetails class, added scope as prototype.

@Scope("prototype")
@Component
public class UserDetails {
//Properties
//Setter & Getters
// Methods
}

Now test from Main application class, whether we are getting new Instance or not for every
request of Bena Object UserDetails from Spring Container.

package com.tek.teacher.products;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringComponentDemo {

public static void main(String[] args) {


AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext();

context.register(BeansConfiguration.class);
context.scan("com.tek.*");
context.refresh();

// UserDetails Component
UserDetails userDetails = context.getBean(UserDetails.class);
System.out.println(userDetails);

UserDetails userTwo = context.getBean(UserDetails.class);


System.out.println(userTwo);

}
}

Output:
com.tek.teacher.UserDetails@74f6c5d8
com.tek.teacher.UserDetails@27912e3

NOTE: Below four are available only if you use a web-aware ApplicationContext i.e. inside
Web applications.

81 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ request
➢ session
➢ application
➢ globalsession

Auto Wiring In Spring


➢ Autowiring feature of spring framework enables you to inject the object dependency
implicitly.
➢ Autowiring can't be used to inject primitive and string values. It works with reference
only.
➢ It requires the less code because we don't need to write the code to inject the
dependency explicitly.
➢ Autowired is allows spring to resolve the collaborative beans in our beans. Spring boot
framework will enable the automatic injection dependency by using declaring all the
dependencies in the configurations.
➢ We will achieve auto wiring with an Annotation @Autowired

Auto wiring will be achieved in multiple ways/modes.

Auto Wiring Modes:

➢ no
➢ byName
➢ byType
➢ constructor

no: It is the default autowiring mode. It means no autowiring by default.


byName: The byName mode injects the object dependency according to name of the
bean. In such case, property name and bean name must be same. It internally calls setter
method.
byType: The byType mode injects the object dependency according to type. So property
name and bean name can be different. It internally calls setter method.
constructor: The constructor mode injects the dependency by calling the constructor of
the class. It calls the constructor having large number of parameters.

In XML configuration, we will enable auto wring between Beans as shown below.

<bean id="a" class="org.sssit.A" autowire="byName">


…….
</bean>

In Annotation Configuration, we will use @Autowired annotation.

82 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


We can use @Autowired in following methods.

1. On properties
2. On setter
3. On constructor

@Autowired on Properties:

Let’s see how we can annotate a property using @Autowired. This eliminates the need
for getters and setters.

First, Let’s Define a bean : Address.

package com.dilip.account;

import org.springframework.stereotype.Component;

@Component
public class Address {

private String streetName;


private int pincode;

public String getStreetName() {


return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public int getPincode() {
return pincode;
}
public void setPincode(int pincode) {
this.pincode = pincode;
}
@Override
public String toString() {
return "Address [streetName=" + streetName + ", pincode=" + pincode + "]";
}
}

Now Define, Another component class Account and define Address type property inside as a
Dependency property.

package com.dilip.account;

83 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


import org.springframework.beans.factory.annotation.Autowired;

@Component
public class Account {

private String name;


private long accNumber;

// Field/Property Level
@Autowired
private Address addr;

public String getName() {


return name;
}
public void setName(String name) {
this.name = name;
}
public long getAccNumber() {
return accNumber;
}
public void setAccNumber(long accNumber) {
this.accNumber = accNumber;
}
public Address getAddr() {
return addr;
}
public void setAddr(Address addr) {
this.addr = addr;
}
}

➢ Create a configuration class, and define Component Scan packages to scan all packages.

package com.dilip.account;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.dilip.*")
public class BeansConfiguration {

➢ Now Define, Main class and try to get Account Bean object and check really Address
Bean Object Injected or Not.

84 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


package com.dilip.account;

import
org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringAutowiringDemo {

public static void main(String[] args) {


AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext();
context.register(BeansConfiguration.class);
context.refresh();

// UserDetails Component
Account account = (Account) context.getBean(Account.class);
//Getting Injected Object of Address
Address address = account.getAddr();
address.setPincode(500072);

System.out.println(address);
}
}

Output:
Address [streetName=null, pincode=500072]

So, Dependency Object Address injected in Account Bean Object implicitly, with @Autowired
on property level.

Autowiring with Multiple Bean ID Configurations with Single Bean/Component Class:

Let’s Create Bean class: Below class Bean Id is : home

package com.hello.spring.boot.employees;

import org.springframework.stereotype.Component;

@Component("home")
public class Addresss {

private String streetName;


private int pincode;

public String getStreetName() {


return streetName;

85 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}

public void setStreetName(String streetName) {


this.streetName = streetName;
}

public int getPincode() {


return pincode;
}

public void setPincode(int pincode) {


this.pincode = pincode;
}

public void printAddressDetails() {


System.out.println("Street Name is : " + this.streetName);
System.out.println("Pincode is : " + this.pincode);
}

➢ For above Address class create a Bean configuration in Side Configuration class.

package com.hello.spring.boot.employees;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.hello.spring.boot.*")
public class BeansConfig {

@Bean("hyd")
Addresss createAddress() {
Addresss a = new Addresss();
a.setPincode(500067);
a.setStreetName("Gachibowli");
return a;
}

➢ Now Autowire Address in Employee class.

package com.hello.spring.boot.employees;

86 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component("emp")
public class Employee {

private String lastName;


private long mobile;

@Autowired
private Addresss add;

public String getLastName() {


return lastName;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}

public long getMobile() {


return mobile;
}

public void setMobile(long mobile) {


this.mobile = mobile;
}

public Addresss getAdd() {


return add;
}

public void setAdd(Addresss add) {


this.add = add;
}
}

➢ Now Test which Address Object Injected by Container i.e. either home or hyd bean
object.

package com.hello.spring.boot.employees;

import
org.springframework.context.annotation.AnnotationConfigApplicationContext;

87 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


public class AutowiringTestMainApp {

public static void main(String[] ar) {

AnnotationConfigApplicationContext context = new


AnnotationConfigApplicationContext();
context.register(BeansConfig.class);
context.refresh();

Employee empployee = (Employee) context.getBean("emp");


Addresss empAdd = empployee.getAdd();
System.out.println(empAdd);

}
}
We got an exception now as,

Exception in thread "main"


org.springframework.beans.factory.UnsatisfiedDependen
cyException: Error creating bean with name 'emp':
Unsatisfied dependency expressed through field 'add':
No qualifying bean of type
'com.hello.spring.boot.employees.Addresss' available:
expected single matching bean but found 2: home,hyd

i.e. Spring Container unable to inject Address Bean Object into Employee Object because of
Ambiguity/Confusion like in between home or hyd bean Objects of Address type.

To resolve this Spring provided one more annotation called as @Qualifier

@Qualifier:

By using the @Qualifier annotation, we can eliminate the issue of which bean needs to be
injected. There may be a situation when you create more than one bean of the same
type and want to wire only one of them with a property. In such cases, you can use
the @Qualifier annotation along with @Autowired to remove the confusion by specifying
which exact bean will be wired.

We need to take into consideration that the qualifier name to be used is the one declared in
the @Component or @Bean annotation.

Now add @Q on Address filed, inside Employee class.

package com.hello.spring.boot.employees;

88 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component("emp")
public class Employee {

private String lastName;


private long mobile;

@Qualifier("hyd")
@Autowired
private Addresss add;

public String getLastName() {


return lastName;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}
public long getMobile() {
return mobile;
}
public void setMobile(long mobile) {
this.mobile = mobile;
}
public Addresss getAdd() {
return add;
}
public void setAdd(Addresss add) {
this.add = add;
}
}

➢ Now Test which Address Bean Object with bean Id “hyd” Injected by Container.

package com.hello.spring.boot.employees;

import
org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class AutowiringTestMainApp {

public static void main(String[] ar) {

89 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext();
context.register(BeansConfig.class);
context.refresh();

Employee empployee = (Employee) context.getBean("emp");


Addresss empAdd = empployee.getAdd();
System.out.println(empAdd.getPincode());
System.out.println(empAdd.getStreetName());

Output:
500067
Gachibowli

i.e. Address Bean Object Injected with Bean Id called as hyd into Employee Bean Object.

@Primary:
There's another annotation called @Primary that we can use to decide which bean to
inject when ambiguity is present regarding dependency injection. This annotation defines a
preference when multiple beans of the same type are present. The bean associated with
the @Primary annotation will be used unless otherwise indicated.

Now add One more @Bean config for Address class inside Configuration class.

package com.hello.spring.boot.employees;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
@ComponentScan("com.hello.spring.boot.*")
public class BeansConfig {

@Bean("hyd")
Addresss createAddress() {
Addresss a = new Addresss();
a.setPincode(500067);
a.setStreetName("Gachibowli");
return a;
}

90 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@Bean("banglore")
@Primary
Addresss bangloreAddress() {
Addresss a = new Addresss();
a.setPincode(560043);
a.setStreetName("Banglore");
return a;
}

In above, we made @Bean("banglore") as Primary i.e. by Default bean object with ID


“banglore” should be injected out of multiple Bean definitions of Address class when
@Qulifier is not defined with @Autowired.

package com.hello.spring.boot.employees;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component("emp")
public class Employee {

private String lastName;


private long mobile;

//No @Qualifier Defined


@Autowired
private Addresss add;

public String getLastName() {


return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public long getMobile() {
return mobile;
}
public void setMobile(long mobile) {
this.mobile = mobile;
}
public Addresss getAdd() {
return add;
}

91 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


public void setAdd(Addresss add) {
this.add = add;
}
}
Output:
560043
Banglore

I.e. Address Bean Object with “banglore" injected in Employee object level.

NOTE: if both the @Qualifier and @Primary annotations are present, then
the @Qualifier annotation will have precedence/priority. Basically, @Primary defines a
default, while @Qualifier is very specific to Bean ID.

Autowiring With Interface and Implemented Classes:

In Java, Interface reference can hold Implemented class Object. With this rule, We can
Autowire Interface references to inject implemented component classes.

Now Define an Interface: Animal

package com.dilip.auto.wiring;

public interface Animal {


void printNameOfAnimal();
}

Now Define A class from interface : Tiger

package com.dilip.auto.wiring;

import org.springframework.stereotype.Component;

@Component
public class Tiger implements Animal {
@Override
public void printNameOfAnimal() {
System.out.println("I am a Tiger ");
}
}

➢ Now Define a Configuration class for component scanning.

package com.dilip.auto.wiring;

import org.springframework.context.annotation.ComponentScan;

92 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.dilip.*")
public class BeansConfig {

➢ Now Autowire Animal type property in any other Component class i.e. Dependency of
Animal Interface implemented class Object Tiger should be injected.

package com.dilip.auto.wiring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AnimalManagement {

@Autowired
//Interface Type Property
Animal animal;

Now Test, Animal type property injected with what type of Object.

package com.dilip.auto.wiring;

import
org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class AutoWringDemo {

public static void main(String[] args) {

AnnotationConfigApplicationContext context = new


AnnotationConfigApplicationContext();
context.register(BeansConfig.class);
context.refresh();

// Getting AnimalManagement Bean Object


AnimalManagement animalMgmt =
context.getBean(AnimalManagement.class);

animalMgmt.animal.printNameOfAnimal();

93 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}

Output:
I am a Tiger

So, implicitly Spring Container Injected one and only implanted class Tiger of Animal Interface
inside Animal Type reference property of AnimalManagement Object.

If we have multiple Implemented classes for same Interface i.e. Animal interface, How
Spring Container deciding which implanted Bean object should Injected?

➢ Define one more Implementation class of Animal Interface : Lion

package com.dilip.auto.wiring;

import org.springframework.stereotype.Component;

@Component("lion")
public class Lion implements Animal {
@Override
public void printNameOfAnimal() {
System.out.println("I am a Lion ");
}
}

Now Test, Animal type property injected with what type of Object either Tiger or Lion.

package com.dilip.auto.wiring;

import
org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class AutoWringDemo {

public static void main(String[] args) {

94 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext();
context.register(BeansConfig.class);
context.refresh();

// Getting AnimalManagement Bean Object


AnimalManagement animalMgmt =
context.getBean(AnimalManagement.class);
animalMgmt.animal.printNameOfAnimal();

We got an Exception as,

Exception in thread "main"


org.springframework.beans.factory.UnsatisfiedDependencyExcepti
on: Error creating bean with name 'animalManagement':
Unsatisfied dependency expressed through field 'animal': No
qualifying bean of type 'com.dilip.auto.wiring.Animal'
available: expected single matching bean but found 2:
lion,tiger

So to avoid again this ambiguity between multiple implementation of single interface, again
we can use @Qualifier with Bean Id or Component Id.

package com.dilip.auto.wiring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component

95 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


public class AnimalManagement {
@Qualifier("lion")
@Autowired
Animal animal;
}

Now it will inject only Lion Object inside AnimalManagement Object as per Qualifier
annotation value out of lion and tiger bean objects.

Run again now AutoWringDemo.java

Output :
I am a Lion.

Can we inject Default implemented class Object out of multiple implementation classes
into Animal reference if not provided any Qualifier value?

Yes, we can inject default Implementation bean Object of Interface. We should mark one class
as @Primary. Now I marked Tiger class as @Primary and removed @Qualifier from
AnimalManagement.

package com.dilip.auto.wiring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AnimalManagement {
@Autowired
Animal animal;
}

Run again now AutoWringDemo.java

Output :
I am a Tiger

96 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Types of Dependency Injection with Annotations :
The process where objects use their dependent objects without a need to define or
create them is called dependency injection. It's one of the core functionalities of the Spring
framework.

We can inject dependent objects in three ways, using:

Spring Framework supporting 3 types if Dependency Injection .

1. Filed/Property level Injection (Only supported Via Annotations )


2. Setter Injection
3. Constructor Injection

Filed Injection:
As the name says, the dependency is injected directly in the field, with no constructor
or setter needed. This is done by annotating the class member with the @Autowired
annotation. If we define @Autowired on property/field name level, then Spring Injects
Dependency Object directly into filed.

Requirement : Address id Dependency of Employee class.

Address.java : Created as Component class

package com.dilip.spring;

import org.springframework.stereotype.Component;

@Component
public class Address {

private String city;


private int pincode;

public Address() {
System.out.println("Address Object Created.");
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getPincode() {
return pincode;
}
public void setPincode(int pincode) {
this.pincode = pincode;

97 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}
}
Employee.java : Component class with Dependency Injection.

package com.dilip.spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Employee {

private String empName;


private double salary;

//Field Injection
@Autowired
private Address address;

public Employee(Address address ) {


System.out.println("Employee Object Created");
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
System.out.println("This is etter method of Emp of Address");
this.address = address;
}
}
We are Defined @Autowired on Address type field in side Employee class, So Spring IOC will
inject Address Bean Object inside Employee Bean Object via field directly.

98 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Testing DI:

package com.dilip.spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class DiMainAppDemo {

public static void main(String[] args) {


AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
context.scan("com.*");
context.refresh();

Employee emp = context.getBean(Employee.class);


System.out.println(emp);
System.out.println(emp.getAddress());

}
}

Output:
Address Object Created.
Employee Object Created
Address Object Created.
com.dilip.spring.Employee@791f145a
com.dilip.spring.Address@38cee291

Setter Injection Overview:

Setter injection uses the setter method to inject dependency on any Spring-
managed bean. Well, the Spring IOC container uses a setter method to inject dependency
on any Spring-managed bean. We have to annotate the setter method with the
@Autowired annotation.

Let's create an interface and Impl. Classes in our project.

Interface : MessageService.java

package com.dilip.setter.injection;

public interface MessageService {


void sendMessage(String message);
}

Impl. Class : EmailService.java

99 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


package com.dilip.setter.injection;

import org.springframework.stereotype.Component;

@Component("emailService")
public class EmailService implements MessageService {

@Override
public void sendMessage(String message) {
System.out.println(message);
}
}

We have annotated EmailService class with @Component annotation so the Spring


container automatically creates a Spring bean and manages its life cycle.

Impl. Class : SMSService.java

package com.dilip.setter.injection;

import org.springframework.stereotype.Component;

@Component("smsService")
public class SMSService implements MessageService {
@Override
public void sendMessage(String message) {
System.out.println(message);
}
}

We have annotated SMSService class with @Component annotation so the Spring container
automatically creates a Spring bean and manages its life cycle.

MessageSender.java
In setter injection, Spring will find the @Autowired annotation and call the setter to
inject the dependency.

package com.dilip.setter.injection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
public class MessageSender {

100 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


private MessageService messageService;

//At setter method level.


@Autowired
public void setMessageService(@Qualifier("emailService") MessageService
messageService) {
this.messageService = messageService;
System.out.println("setter based dependency injection");
}
public void sendMessage(String message) {
this.messageService.sendMessage(message);
}
}
@Qualifier annotation is used in conjunction with @Autowired to avoid confusion
when we have two or more beans configured for the same type.

➢ Now create a Test class to validate, dependency injection with setter Injection.

package com.dilip.setter.injection;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Client {


public static void main(String[] args) {
String message = "Hi, good morning have a nice day!.";
ApplicationContext context = new AnnotationConfigApplicationContext();
context.scan(“com.dilip.*”);
MessageSender messageSender = context.getBean(MessageSender.class);
messageSender.sendMessage(message);
}
}

Output:
setter based dependency injection
Hi, good morning have a nice day!.

Injecting Multiple Dependencies using Setter Injection:

Let's see how to inject multiple dependencies using Setter injection. To inject multiple
dependencies, we have to create multiple fields and their respective setter methods. In the
below example, the MessageSender class has multiple setter methods to inject multiple
dependencies using setter injection:

package com.dilip.setter.injection;

101 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
public class MessageSender {

private MessageService messageService;

private MessageService smsService;

@Autowired
public void setMessageService(@Qualifier("emailService") MessageService
messageService) {
this.messageService = messageService;
System.out.println("setter based dependency injection");
}

@Autowired
public void setSmsService(MessageService smsService) {
this.smsService = smsService;
System.out.println("setter based dependency injection 2");
}

public void sendMessage(String message) {


this.messageService.sendMessage(message);
this.smsService.sendMessage(message);
}
}

➢ Now Run Client.java, One more time to see both Bean Objects injected or not.
Output:
setter based dependency injection 2
setter based dependency injection
Hi, good morning have a nice day!.
Hi, good morning have a nice day!.

102 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Constructor Injection:

Constructor injection uses the constructor to inject dependency on any Spring-managed


bean. Well, the Spring IOC container uses a constructor to inject dependency on any Spring-
managed bean. In order to demonstrate the usage of constructor injection, let's create a few
interfaces and classes.
MessageService.java

package com.dilip.setter.injection;

public interface MessageService {


void sendMessage(String message);
}

EmailService.java

package com.dilip.setter.injection;

import org.springframework.stereotype.Component;

103 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@Component
public class EmailService implements MessageService {

@Override
public void sendMessage(String message) {
System.out.println(message);
}
}

We have annotated EmailService class with @Component annotation so the Spring container
automatically creates a Spring bean and manages its life cycle.

SMSService.java

package com.dilip.setter.injection;

import org.springframework.stereotype.Component;

@Component("smsService")
public class SMSService implements MessageService {
@Override
public void sendMessage(String message) {
System.out.println(message);
}
}

We have annotated SMSService class with @Component annotation so the Spring container
automatically creates a Spring bean and manages its life cycle.
MessageSender.java

package com.dilip.setter.injection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
public class MessageSender {

private MessageService messageService;

//Constructor level Auto wiring


@Autowired
public MessageSender(@Qualifier("emailService") MessageService
messageService) {
this.messageService = messageService;
System.out.println("constructor based dependency injection");

104 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}

public void sendMessage(String message) {


this.messageService.sendMessage(message);
}
}

➢ Now create a Configuration class: AppConfig.java

package com.dilip.setter.injection;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.dilip.*")
public class AppConfig {

➢ Now create a Test class to validate, dependency injection with setter Injection.

package com.dilip.setter.injection;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Client {

public static void main(String[] args) {

String message = "Hi, good morning have a nice day!.";

ApplicationContext applicationContext = new


AnnotationConfigApplicationContext(AppConfig.class);

MessageSender messageSender = applicationContext.getBean(MessageSender.class);


messageSender.sendMessage(message);
}
}

Output:
constructor based dependency injection
Hi, good morning have a nice day!.

105 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


How to Declare Types of Autowiring with Annotations?

When we discussed of autowiring with beans XML configurations, Spring Provided 4 types
autowiring configuration values for autowire attribute of bean tag.

1. no
2. byName
3. byType
4. constructor

But with annotation Bean configurations, we are not using these values directly because we
are achieving same functionality with @Autowired and @Qualifier annotations directly or
indirectly.

Let’s compare functionalities with annotations and XML attribute values.

no : If we are not defined @Autowired on field/setter/constructor level, then Spring not


injecting Dependency Object in side composite Object.

byType: If we define only @Autowired on field/setter/constructor level then, Spring injecting


Dependency Object in side composite Object specific to Datatype of Bean. This works when
we have only one Bean Configuration of Dependent Object.

byName: If we define @Autowired on field/setter/constructor level along with @Qualifeir


then, Spring injecting Dependency Object in side composite Object specific to Bean ID.

constructor : when we are using @Autowired and @Qulaifier along with constructor, then
Spring IOC container will inject Dependency Object via constructor.

So explicitly we no need to define any autowiring type with annotation based Configurations
like in XML configuration.

106 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Bean life cycle in Spring:
The Spring Bean life cycle is the heartbeat of any Spring application, dictating how
beans are created, initialized, and eventually destroyed. The lifecycle of any object means
when & how it is born, how it behaves throughout its life, and when & how it dies. Similarly,
the bean life cycle refers to when & how the bean is instantiated, what action it performs
until it lives, and when & how it is destroyed.

Spring bean is a Java object managed by the Spring IoC container. These objects can
be anything, from simple data holders to complex business logic components. The magic lies
in Spring’s ability to manage the creation, configuration, and lifecycle of these beans.

Bean life cycle is managed by the spring container. When we run the program then,
first of all, the spring container gets started. After that, the container creates the instance of
a bean as per configuration, and then dependencies are injected. After utilization of Bean
Object and then finally, the bean is destroyed when the spring container is closed.

Therefore, if we want to execute some code on the bean instantiation and just after
closing the spring container, then we can write that code inside the custom init() method and
the destroy() methods.

Benefits of Exploring the Spring Bean Life Cycle:

➢ Resource Management: As you traverse the life cycle stages of Bean Object, you’re in
control of resources. This translates to efficient memory utilization and prevents resource
leaks, ensuring your application runs like a well configured machine.

107 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ Customization: By walking through the life cycle stages, you can inject custom logic at
strategic points. This customization allows your beans to adapt to specific requirements,
setting the stage for a flexible and responsive application.
➢ Dependency Injection: Understanding the stages of bean initialization also resolves the
magic of dependency injection. You’ll learn how beans communicate, collaborate, and
share information, building a cohesive application architecture.

➢ Debugging: With a firm grasp of the life cycle, troubleshooting becomes very easy. By
tracing a bean’s journey through each stage, you can pinpoint issues and enhance the
overall stability of your application.

Defining Bean Life Cycle Methods:

Spring allows us to attach custom actions to bean creation and destruction. We can
do it by implementing the InitializingBean and DisposableBean interfaces.

InitializingBean:

InitializingBean is an interface in the Spring Framework that allows a bean to perform


initialization tasks after its properties have been set. It defines a single method,
afterPropertiesSet(), which a bean class must implement to carry out any initialization logic.

When the Spring container initializes the Bean instance, it will first set any properties
configured, and then it will call the afterPropertiesSet() method automatically. This allows
you to perform any custom initialization tasks within that method.

DisposableBean:

DisposableBean is another interface in the Spring Framework that complements the


InitializingBean. While InitializingBean is used for performing initialization tasks,
DisposableBean is used for performing cleanup or disposal tasks when a bean is being
removed from the Spring container.

The DisposableBean interface defines a single method, destroy(), which a bean class
must implement to carry out any cleanup logic.

When the Spring container is shutting down or removing the bean, it will call the destroy()
method automatically, allowing you to perform any necessary cleanup tasks.

Defining Bean Life Cycle Methods with Beans:

➢ Create a Bean class by implementing both InitializingBean and DisposableBean.

package com.dilip;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

108 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


import org.springframework.stereotype.Component;

@Component
public class Customer implements InitializingBean, DisposableBean {

private int id;


private String name;

public Customer() {
System.out.println("Customer Object is Created");
}

// This will be executed once instance created


@Override
public void afterPropertiesSet() throws Exception {
System.out.println("This is Init logic from afterPropertiesSet()");
System.out.println("Initialization logic goes here");
}

// This will be executed before container instance closing


@Override
public void destroy() throws Exception {
System.out.println("This is destroying logic from destroy()");
System.out.println("Cleanup logic goes here");
}
public int getId() {
return id;
}
public void setId(int id) {
System.out.println("Setter for injecting ID value");
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
System.out.println("Setter for injecting name value");
this.name = name;
}
}

Spring Bean Object Life Cycle followed below steps in an order.

➢ Now get this Bean Object from IOC container.


➢ Once we created or initialized Spring Container, Container starts the process of
Instantiating Bean Objects.
➢ Bean Object will be created/instantiated

109 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ After Bean Object creation , Properties Values will be injected if any available.
➢ All Dependencies will be identified and injected
➢ Now Bean Initialization method i.e. afterPropertiesSet() method logic will be executed by
IOC container one time i.e. this method will be executed once anew Object is created
always by container.
➢ Now Bean Object is ready with all configuration values of properties and initialization
values.
➢ We will always get current object always when we get it from container always.
➢ After utilization of Bean Object, when the Spring container is shutting down or removing
the bean, it will call the destroy() method automatically for every Bean Object, allowing
you to perform any necessary cleanup tasks written as part of the method.
➢ After executing all bean Objects destroy() methods then finally container got closed.

The following image shows the process flow of the Bean Object life cycle.

Spring Bean Life Cycle Flow

➢ Now create Spring IOC container instance and try to get Bean Object and then close the
container Instance.
➢ Creating Beans Configuration class.

package com.dilip;

110 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@ComponentScan("com.dilip")
@Configuration
public class BeansConfiguration {

➢ Now Pass above Configuration class to container.

package com.dilip;

import
org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringBeanLifeCycleDemo {


public static void main(String[] args) {

// Created the Container


AnnotationConfigApplicationContext context =
new
AnnotationConfigApplicationContext();

// Providing Bean Classes information to Container


context.register(BeansConfiguration.class);

// Create/Instantiate Bean Objects


context.refresh();

//Get the Bean Object from Container and Utilize it


Customer customer = context.getBean(Customer.class);
System.out.println(customer);

// Closing the Container


context.close();
}
}

Output:

111 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ Same Process will follow by container internally for every Bean Object of class.

➢ Adding a Bean Method inside Configuration class for another Customer Object and then
we will see same process followed for new Bean Object as usually.

BeansConfiguration.java
package com.dilip;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@ComponentScan("com.dilip")
@Configuration
public class BeansConfiguration {

@Bean(name="customer2")
Customer getCustomer() {
return new Customer();
}
}

➢ Now Execute container creation and closing Lofigc again and observe initialization and
destroy methods executed 2 times for 2 Customer Bean Objects creation.

package com.dilip;

import
org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringBeanLifeCycleDemo {


public static void main(String[] args) {
// Created the Container
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
// Providing Bean Classes information to Container
context.register(BeansConfiguration.class);

112 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


// Create/Instantiate Bean Objects
context.refresh();
// Closing the Container
context.close();
}
}

Output : For Every bean Object, executed both actions of initialization and destroy.

This is how we can define lifecycle methods explicitly to provide instantiation logic and
destruction logic for a bean Object.

Note: Same above approach of writing Bean class with InitializingBean and DisposableBean,
can be followed in Spring Beans XML configuration for a Bean class and Objects.

Question: Do we have any other ways to define life cycle methods apart from
InitializingBean and DisposableBean?

Yes, we have second possibility, the @PostConstruct and @PreDestroy annotations


from Java EE.

Note: Both @PostConstruct and @PreDestroy annotations are part of Java EE. Since Java EE
was deprecated in Java 9, and removed in Java 11, we have to add an additional dependency
in pom.xml to use these annotations.

<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>

Define these annotations on custom methods of Bean instantiation and destroying logic with
out using any Predefined Interfaces from Spring FW.

113 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@PostConstruct:
Spring calls the methods annotated with @PostConstruct only once, just after the
initialization of bean properties i.e. this is a replacement of InitializingBean and its associated
abstract method implementation.

@PreDestroy:
Spring calls the methods annotated with @PreDestroy runs only once, just before
Spring removes our bean from the application context.
Note: @PostConstruct and @PreDestroy annotated methods can have any access level, but
can’t be static.

Example: Bean Class: Customer.java

package com.dilip;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.stereotype.Component;

@Component
public class Customer {

private int id;


private String name;

public Customer() {
System.out.println("Customer Object is Created");
}

@PostConstruct
public void init() {
System.out.println("This is Init logic from init()");
}

@PreDestroy
public void destroy() {
System.out.println("This is destroying logic from destroy()");
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;

114 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}
public void setName(String name) {
this.name = name;
}
}

➢ Beans Configuration Class: BeansConfiguration.java : Created another Bean Instance

package com.dilip;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@ComponentScan("com.dilip")
@Configuration
public class BeansConfiguration {
@Bean(name="customer2")
Customer getCustomer() {
return new Customer();
}
}

➢ Now Execute container creation and closing Lofigc again and observe initialization and
destroy methods executed 2 times for 2 Customer Bean Objects creation.

package com.dilip;

import
org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringBeanLifeCycleDemo {


public static void main(String[] args) {
// Created the Container
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
context.register(BeansConfiguration.class);
context.refresh();
// Closing the Container
context.close();
}
}

Output : For Every bean Object, executed both actions of initialization and destroy.

115 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Question: Can we define custom methods in class for initialization and destruction of a bean
object i.e. without using Pre-Defined Interfaces and Annotations ?

Yes, We can Define custom methods with user defined names of methods of both initialization
and destroying actions.

Bean class: Student.java

package com.dilip;

public class Student {

private int sid;

public Student() {
System.out.println("Student Constructor : Object Created");
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
// For Initialization
public void beanInitialization() {
System.out.println("Bean Initialization Started... ");
}
// For Destruction
public void beanDestruction() {
System.out.println("Bean Destruction Started..... ");
}
}

In XML Configuration :

116 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ Now inside Beans XML file configuration, define which method is Responsible for Bean life
cycle method of initialization and destruction. Spring framework provide 2 pre-defined
attributes init-method and destroy-method as part of <bean> tag .

➢ Configure custom life cycle methods in Beans.xml by using both attributes:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
<bean id="student" class="com.dilip.Student"
init-method="beanInitialization"
destroy-method="beanDestruction">

</bean>
</beans>

➢ Now Instantiate and close Spring Container and then container will execute life cycle
methods as per our configuration of a bean Object.

In Annotation based Configuration :

➢ Spring Framework provided two attributes initMethod and destroyMethod as part of


@Bean annotation. By using these attributes, we will define the method names as
followed.

@Bean(initMethod = "beanInitialization", destroyMethod = "beanDestruction")


Student getStudent() {
return new Student();
}

Question: Why Understand the Spring Bean Life Cycle?

Understanding the life cycle of Spring beans is like having a backstage pass to the inner
workings of your Spring application. A solid grasp of the bean life cycle empowers you to
effectively manage resources, configure beans, and ensure proper initialization and cleanup.
With this knowledge, you can optimize your application’s performance, prevent memory
leaks, and implement custom logic at various stages of a bean’s existence.

117 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


SpringBoot:
Spring and Spring Boot are both Java-based frameworks used for building enterprise-
level applications, particularly in the realm of web and server-side development. However,
they serve slightly different purposes and have some key differences:
Purpose:
Spring: Spring is a comprehensive framework for building Java-based enterprise applications.
It provides a wide range of modules for various concerns such as dependency injection,
aspect-oriented programming, data access, transaction management, and more. Spring is
highly configurable and allows developers to pick and choose which modules they want to use
in their applications.
Spring Boot: Spring Boot is built on top of the Spring framework and is designed to simplify
the process of building and deploying Spring-based applications. It aims to provide an
opinionated way of setting up Spring applications with minimal configuration. Spring Boot
favors convention over configuration, which means it provides sensible defaults and requires
less boilerplate code, making it easier to get started with Spring-based projects.
Configuration:
Spring: Spring applications typically require extensive XML or Java-based configuration to wire
up components and define application behavior. Developers need to configure various aspects
of the application, such as data sources, beans, and transaction management, explicitly.
Spring Boot: Spring Boot uses a "convention over configuration" approach, which means it
comes with sensible defaults for many common configurations. It uses annotations and auto-
configuration to automatically set up the application, reducing the need for explicit
configuration. Developers can still customize the configuration when needed.
Development:
Spring: Developing with Spring often involves writing a significant amount of configuration
code, XML files, and boilerplate code. It provides a lot of flexibility, but this flexibility can lead
to complexity.
Spring Boot: Spring Boot encourages rapid development by providing pre-configured settings
and dependencies. It's optimized for creating production-ready applications with minimal
effort. Developers can focus more on writing business logic and less on infrastructure code.
Dependency Management:
Spring: Developers using Spring typically need to manage dependencies manually, which
involves specifying the versions of libraries they want to use and handling conflicts.
Spring Boot: Spring Boot includes a dependency management system that simplifies the
process of declaring and managing dependencies. It also provides a wide range of pre-
configured dependencies for common tasks.

118 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Embedded Containers:
Spring: Spring applications often require external web containers like Apache Tomcat or Jetty
for deployment.
Spring Boot: Spring Boot includes embedded web containers like Tomcat, Jetty, or Undertow,
making it easier to package and deploy applications as standalone executable JAR files.
In summary, while both Spring and Spring Boot are part of the Spring ecosystem and
can be used to build Java-based applications, Spring Boot focuses on simplifying the
development and deployment process by providing defaults and reducing configuration
overhead, making it an attractive choice for developers looking for a faster way to build
production-ready applications.
Now we are starting Spring Boot and whatever we discussed in Spring framework
everything can be done in Spring boot Application because Spring Boot Internally uses Spring
only.
Here are some key points to introduce Spring Boot:
Rapid Application Development: Spring Boot eliminates the need for extensive boilerplate
configuration that often accompanies traditional Spring projects. It offers auto-configuration,
where sensible defaults are applied based on the dependencies in your classpath. This allows
developers to focus on writing business logic instead of spending time configuring various
components.
Embedded Web Servers: Spring Boot includes embedded web servers, such as Tomcat, Jetty,
or Undertow, which allows you to run your applications as standalone executables without
requiring a separate application server. This feature simplifies deployment and distribution.
Starter POMs: Spring Boot provides a collection of "starter" dependencies, which are
opinionated POMs (Project Object Model) that encapsulate common sets of dependencies for
specific use cases, such as web applications, data access, security, etc. By adding these starters
to your project, you automatically import the required dependencies, further reducing setup
efforts.
Actuator: Spring Boot Actuator is a powerful feature that provides production-ready tools to
monitor, manage, and troubleshoot your application. It exposes various endpoints, accessible
via HTTP or JMX, to obtain valuable insights into your application's health, metrics, and other
operational information.
Configuration Properties: Spring Boot allows you to configure your application using external
properties files, YAML files, or environment variables. This decouples configuration from code,
making it easier to manage application settings in different environments.
Auto-configuration: Spring Boot analyzes the classpath and the project's dependencies to
automatically configure various components. Developers can override this behavior by
providing their own configurations, but the auto-configuration greatly reduces the need for
explicit configuration.

119 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Overall, Spring Boot has revolutionized Java development by simplifying the creation
of robust, production-ready applications. Its emphasis on convention-over-configuration,
auto-configuration, and opinionated defaults makes it an excellent choice for developers
seeking to build modern, scalable, and maintainable Java applications.
Starters In Spring Boot:
In Spring Boot, a "Starter" is a pre-configured set of dependencies that are commonly
used together to build specific types of applications or address particular tasks. Starters
simplify the process of setting up a Spring Boot application by providing a curated collection
of libraries and configuration that are known to work well together for a particular use case.
They help developers get started quickly without having to manually configure each individual
dependency.
Here are some key points about Spring Boot Starters:
Purpose: Spring Boot Starters are designed to streamline the development process by
bundling together dependencies that are commonly used for specific tasks or application
types. They promote the principle of convention over configuration, reducing the amount of
boilerplate code and configuration required.
Dependency Management: Starters include not only the necessary libraries but also pre-
configured settings and defaults for those libraries. This simplifies dependency management,
as developers don't need to worry about specifying versions or managing compatibility issues
between libraries.
Spring Initializr: Spring Initializr is a web-based tool provided by the Spring team that makes
it easy to generate a new Spring Boot project with the desired starters. Developers can select
the starters they need, and Spring Initializr generates a project structure with the necessary
dependencies and basic configuration.
Examples:
spring-boot-starter-web: This starter is commonly used for building web applications.
It includes dependencies for Spring MVC, embedded web server (e.g., Tomcat, Jetty),
and other web-related components.
spring-boot-starter-data-jpa: This starter is used for building applications that interact
with relational databases using the Java Persistence API (JPA). It includes dependencies
for Spring Data JPA, Hibernate, and a database driver.
spring-boot-starter-security: For building secure applications, this starter includes
Spring Security and related dependencies for authentication and authorization.
spring-boot-starter-test: This starter includes testing libraries such as JUnit and Spring
Test for writing unit and integration tests.

120 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Using Spring Boot Starters can significantly accelerate the development process and improve
consistency across projects by ensuring that best practices and compatible libraries are used
together. It's one of the key features that makes Spring Boot a popular choice for building Java-
based microservices and web applications.
Let’s Create Spring application with Spring Boot.
Spring Boot is a Spring module that provides the RAD (Rapid Application Development) feature
to the Spring framework. We can create Spring Boot project mainly in 2 ways.
Using https://start.spring.io web portal:
• Go to https://start.spring.io website. This service pulls in all the dependencies you need
for an application and does most of the setup for you.

• Choose Maven and the language Java, Spring Boot Version we want.
• Click Dependencies and select required modules.
• Now fill all details of Project Metadata like project name and package details.
• Click Generate.
• Download the resulting ZIP file, which is an archive i.e. zip file of application that is
configured with your choices.
• Now you can import project inside Eclipse IDE or any other IDE’s.

Creating From STS ( Spring Tool Suite ) IDE:

STS stands for "Spring Tool Suite." It is an integrated development environment (IDE)
based on Eclipse and is specifically designed for developing applications using the Spring
Framework, including Spring Boot projects. STS provides a range of tools and features that
streamline the development process and enhance productivity for Spring developers.

121 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


STS is a widely used IDE for Spring development due to its rich feature set and seamless
integration with the Spring Framework and related technologies. It provides a productive
environment for building robust and scalable Spring applications, particularly those
leveraging Spring Boot's capabilities. STS is available as a free download and is an excellent
choice for developers working on Spring projects.
➢ Download STS from below link.
https://download.springsource.com/release/STS4/4.18.1.RELEASE/dist/e4.27/spring-tool-
suite-4-4.18.1.RELEASE-e4.27.0-win32.win32.x86_64.self-extracting.jar

➢ It will download STS as a jar file. Double click on jar, it will extract STS software.
➢ Open STS, Now create Project. File -> New -> Spring Starter Project.

➢ Now we can add all our dependencies, and click on finish.

122 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


NOTE: By Default Spring Boot will support Core Module Functionalities i.e. not required to
add any Dependencies in this case.

Now project created and imported to STS Directly.

If we observe, we are not added any jar files manually or externally to project like
however we did in Spring Framework to work with Core Module. This is mot biggest
advantage of Spring Boot Framework because in future when we are working with other
modules specifically, we no need to find out jar files information and no need to add manually.

Now It’s all about writing logic in project instead of thinking about configuration and project
setup.

Created Project Structure:

While Project creation, By default Spring Boot will generates a main method class as shown
in below.

We will discuss about this Generated class in future, but not this point because we should
understand other topics before going internally.

123 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Beans : XML based Configuration:

Create a Bean class : Student.java

package com.dilip.beans;

public class Student {

private String name;


private int studentID;
private long mobile;

public Student() {
System.out.println("Student Object Created");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStudentID() {
return studentID;
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
public long getMobile() {
return mobile;
}
public void setMobile(long mobile) {
this.mobile = mobile;
}
}

➢ Now create Benas XML file inside resources folder : beans.xml

<?xml version="1.0" encoding="UTF-8"?>


<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.xsd">

<bean id ="student" class="com.dilip.beans.Student">


<property name="name" value="Dilip Singh"></property>

124 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


<property name="studentID" value="1111"></property>
<property name="mobile" value="8826111377"></property>
</bean>
</beans>

Now Create Main Method Class:

package com.dilip.beans;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestBeans {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student s1 = (Student) context.getBean("student");
System.out.println(s1);
}
}

Now Execute Program : Output:

Student Object Created


com.dilip.beans.Student@1c7696c6

Project Folder Structure :

125 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


NOTE: If we observe above logics, we are written same code of Spring Framework
completely. Means, Nothing new in spring boot w.r.to Coding/Logic point of view because
Spring Boot itself a Spring Project.

So Please Practice all examples of Spring framework what we discussed previously w.r.to
XML and Java Based configuration.

@Value Annotation:
This @Value annotation can be used for injecting values into fields in Spring-managed
beans, and it can be applied at the field or constructor/method parameter level. We can read
spring environment variables as well as system variables using @Value annotation.

Package: org.springframework.beans.factory.annotation.Value;

@Value - Default Value:


We can assign default value to a class property using @Value annotation.

@Value("Dilip Singh")
private String defaultName;

So, defaultName value is now Dilip Singh

@Value annotation argument can be a string only, but spring tries to convert it to the
specified type. Below code will work fine and assign the boolean and int values to the variable.

@Value("true")
private boolean isJoined;

@Value("10")
private int count;

@Value – injecting Values from Properties File:

As part of @Value we should pass property name as shown in below signature along with
Variables.

Syntax: @Value("${propertyName}")

We will define properties in side properties/yml file, we can access them with @Value
annotation.

application.properties:

bank.name=CITI BANK
bank.main.location=USA
bank.total.emplyees=40000
citi.db.userName=localDatabaseName

126 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Now we can access any of above values in our any of Spring Bean classes with @Value
annotation. For example, Accessing from Component class.

package com.bank.city;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class CitiBank {

@Value("${citi.db.userName}")
String dbName;

@Value("${bank.total.emplyees}")
int totalEmplyeCount;

public String getDbName() {


return dbName;
}
public void setDbName(String dbName) {
this.dbName = dbName;
}
public int getTotalEmplyeCount() {
return totalEmplyeCount;
}
public void setTotalEmplyeCount(int totalEmplyeCount) {
this.totalEmplyeCount = totalEmplyeCount;
}
}

In Spring Framework Application, we have to Define an annotation @PropertySource on


Configuration class level by passing properties file name externally. So then Spring
framework, Annotation providing a convenient and declarative mechanism for adding a
Property Sources to Spring Environment. To be used in conjunction with @Configuration
classes.

package com.bank.city.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@ComponentScan("com.*")
@Configuration
@PropertySource("application.properties")
public class BeansConfiguration {

127 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}

If it is SpringBoot Application, then we no need to add @PropertySource, because internally


SpringBoot framework will take care of application.properties file by default and added to
Spring environment.

Testing :

Sometimes, we need to inject List of values for one property. It would be convenient
to define them as comma-separated values for the single property in the properties file and
to inject into an array.

List of values in Property: trainingCourses = java,python,angular

Inside Bean class, we will write below logic to inject values.

@Value(“${trainingCourses}”)
List<String> courses;

Map property : We can also use the @Value annotation to inject a Map property.

First, we'll need to define the property in the {key: ‘value' } form in our properties file:

Note: the values in the Map must be in single quotes.


value in Property: course.fees={java:'2000', python:'3000', oracle:'1000'}
Now we can inject this value from the property file as a Map: Syntax change in Attribute
definition of @Value annotation.

@Value("#{${course.fees}}")
Map<String, Integer> prices;

128 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@Value with methods:

@Value is defined at method level, If the method has multiple arguments, then every
argument value is mapped from the method annotation.

@Value("Test")
public void printValues(String value1, String value2){

From above, value1 & value2 injected with value Test.

If we want different values for different arguments then we can use @Value annotation
directly with the argument.

@Value("Test")
public void printValues(String value1, @Value("Data") String value2){

// value1=Test, value2=Data

Similarly we can use @Value along with Constructor arguments.

@Order Annotation:

In Spring Boot, the @Order annotation is used to specify the order in which Spring
beans should be instantiated and initialized. It's often used when you have multiple
components that implement the same interface or extend the same class, and you want to
control the order in which they are injected by Spring Container as part of Collection
Instances. The @Order annotation in Spring defines the sorting order of beans or
components.

Use of @Order annotation:

Many times we face situations where we require the beans or dependencies to be injected in
a particular order. Some of the common use-cases are:

• For injecting the collection of ordered beans, components


• Sequencing the execution CommandLineRunner or ApplicationRunner in Spring Boot
• Applying the filters in an ordered way in Spring Security

Package: org.springframework.core.annotation.Order;

129 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ Apply the @Order annotation to the classes you want to order. You can apply it to classes,
methods, or fields, depending on your use case.

@Component
@Order(1)
public class MyFirstComponent {
// ...
}

@Component
@Order(2)
public class MySecondComponent {
//...
}

@Component
@Order(-1)
public class MyHighPriorityComponent {
//….
}

In this example, MyFirstComponent will be injected before MySecondComponent because it


has a lower order value (1 vs. 2) i.e. lower value takes higher precedence.

Components with a lower order value are processed before those with a higher order value.
We can also use negative values if you want to indicate a higher precedence. For example, if
we want a component to have the highest precedence, you can use a negative values like -1.
If you have multiple beans with the same order value, the initialization order among them is
not guaranteed.

Example: For this, I’m taking a very simple example. Here, Let’s have a Notification interface.
This interface has one method send(). We also have different implementations of this
interface. Basically, each implementation represents a different channel or medium to send
notifications.

130 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Interface : Notification.java

package com.dilip.notifications;

/*
* A Simple interface having just one method send()
*/
public interface Notification{
void send();
}

Implemented Classes : SmsNotification.java

package com.dilip.notifications;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(1)
public class SmsNotification implements Notification {

public SmsNotification() {
System.out.println("SmsNotification Service created.");
}
@Override
public void send() {
System.out.println("Sending SMS Notification Handler");
}
}

➢ EmailNotification.java

package com.dilip.notifications;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(2)
public class EmailNotification implements Notification {

public EmailNotification() {
System.out.println("EmailNotification Service Created.");
}

131 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@Override
public void send() {
System.out.println("Sending Email Notification");
}
}

➢ TwitterNotification.java

package com.dilip.notifications;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(3)
public class TwitterNotification implements Notification {

public TwitterNotification() {
System.out.println("TwitterNotification Service created.");
}

@Override
public void send() {
System.out.println("Sending Twitter Notification Handler");
}
}

So, let’s now try sending a notification to all possible channels i.e. through all available
implementations of Notification. To do so, we will need List<Notification> to be injected.

In our ordering, we have given the highest priority to SmsNotification by giving @Order(1) as
compared to others. So, that should be the first in the output. Also, we have given no 3 to
TwitterNotification so this should come in the last always. In Below Same List Objects of
Notifications component order will be followed as we defined via @Order.

package com.dilip.notifications;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AllNotifications {

@Autowired

132 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


private List<Notification> notifications;

public List<Notification> getNotifications() {


return notifications;
}
public void setNotifications(List<Notification> notifications) {
this.notifications = notifications;
}
}

Testing:

package com.dilip;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.dilip.notifications.AllNotifications;

@SpringBootApplication
public class OrderComponentsApplication {
public static void main(String[] args) {
ApplicationContext context
= SpringApplication.run(OrderComponentsApplication.class, args);

//Getting All Notifications and calling send methods


AllNotifications notifications = context.getBean(AllNotifications.class);
notifications.getNotifications().stream().forEach(v -> v.send());
}
}

Output: And here you go. It printed in the exact order we mentioned.

So, Spring Sorted the Notification Bean Objects while adding to List instance internally by
following @Order value.

133 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Note: Ordering works at the time of injection only

Since we have annotated with @Order you believe that their instantiation will also follow the
same order, right?

However, that’s not the case. Though the concept of @Order looks very simple, sometimes
people get confused about its behaviour. The ordering works only at the time of injecting the
beans/services, not at the time of their creation.

So, clearly we can see that the order of creation is different that order of injection from above
execution.

Ordering @Bean Factory Methods:

We can also order Injecting Objects of Collections in Spring by putting @Order annotation on
the @Bean methods.

Consider, there are three @Bean methods and each of them returns a String.

@Bean
@Order(2)
public String getString1() {
return "one";
}

@Bean
@Order(3)
String getString2() {
return "two";
}

@Bean
@Order(1)
String getString3() {
return "three";
}

When we auto wire them into a List

private final List<String> stringList;

@Autowired
public FileProcessor(List<String> stringList) {
this.stringList = stringList;
}

Spring sorts the beans in the specified order. Thus, printing the list we get:

134 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


three
one
two

Similarly, when we are injecting a multiple beans of same type as a collection we can set a
custom sort order on the individual bean classes.

Ordered Interface:

In Spring Framework & Spring Boot, the Ordered interface is used to provide a way to
specify the order in which objects should be processed. This interface defines a single method,
getOrder(), which returns an integer value representing the order of the object. Objects with
lower order values are processed before objects with higher order values. This is similar to
@Order Annotation functionality.

Here's how you can use the Ordered interface:

1. Implement the Ordered interface in our component class:

import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

@Component
public class MyOrderedComponent implements Ordered {

@Override
public int getOrder() {
// Specify the order of this component
// Lower values mean higher precedence
return 1;
}

// Other methods and properties of your component


}

In this example, the MyOrderedComponent class implements the Ordered interface and
specifies an order value of 1.

2. When Spring Boot initializes the beans, it will take into account the getOrder() method to
determine the processing order of your component.

3. Components that implement Ordered interface can be used in various contexts where
order matters, such as event listeners, filters, and other processing tasks.

4. To change the processing order, simply modify the return value of the getOrder() method.
Lower values indicate higher precedence.

135 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


In this example, the MyOrderedComponent bean will be initialized based on the order
specified in its getOrder() method. You can have multiple beans that implement Ordered, and
they will be processed in order according to their getOrder() values. Lower values indicate
higher precedence.

Runners in SpringBoot :
Runners in Spring Boot are beans that are executed after the Spring Boot application has been
started. They can be used to perform any one-time initialization tasks, such as loading data,
configuring components, or starting background processes.

Spring Boot provides two types of runners:

1. ApplicationRunner : This runner is executed after the Spring context has been loaded, but
before the application has started. This means that you can use it to access any beans that
have been defined in the Spring context.
2. CommandLineRunner : This runner is executed after the Spring context has been loaded,
and after the command-line arguments have been parsed. This means that you can use it
to access the command-line arguments that were passed to the application.

To implement a runner, you need to create a class that implements the appropriate interface.
The run() method of the interface is where you will put your code that you want to execute.

CommandLineRunner:

In Spring Boot, CommandLineRunner is an interface that allows you to execute code


after the Spring Boot application has started and the Spring Application Context has been fully
initialized. We can use it to perform tasks or run code that need to be executed once the
application is up and running.

Here's how you can use CommandLineRunner in a Spring Boot application:

1. Create a Java class that implements the CommandLineRunner interface. This class should
override the run() method, where you can define the code you want to execute.
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// Your code to be executed after the application starts
System.out.println("Hi from CommandLineRunner!");
// You can put any initialization logic or tasks here.
}
}

136 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Note that @Component annotation is used here to make Spring automatically detect and
instantiate this class as a Spring Bean.

2. When we run our Spring Boot application, the run() method of your CommandLineRunner
implementation will be executed automatically after the Spring context has been initialized.

3. We can have multiple CommandLineRunner implementations, and they will be executed


in the order specified by the @Order annotation or the Ordered interface if you want to
control the execution order.

Here's an example of how to run a Spring Boot application with a CommandLineRunner:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TestingApplication {
public static void main(String[] args) {
SpringApplication.run(TestingApplication.class, args);
}
}

When we run this Spring Boot application, the run() method of your MyCommandLineRunner
class (or any other CommandLineRunner implementations) will be executed after the
application has started.

This is a useful mechanism for tasks like database initialization, data loading, or any other
setup code that should be executed once your Spring Boot application is up and running.

137 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Similarly, we can Create Multiple CommandLineRunner implementation Component Classes,
these all classes run() methods logic will be executed when we execute our Spring Boot
Application. To define execution order of all CommandLineRunner implementation classes,
we have to declare either @Order annotation or should implement Ordered interface.
Using @Order Annotation :

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Order(2)
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// Your code to be executed after the application starts
System.out.println("Hi from CommandLineRunner!");
// You can put any initialization logic or tasks here.
}
}

Using Ordered Interface :

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

@Component
public class MyCommandLineRunnerTwo implements CommandLineRunner, Ordered {
@Override
public void run(String... args) throws Exception {
System.out.println("Hi from MyCommandLineRunnerTwo!");
// You can put any initialization logic or tasks here.
}
@Override
public int getOrder() {
return 1;
}
}

Testing: Run Our Spring Boot Application.

138 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


ApplicationRunner:
In Spring Boot, the ApplicationRunner interface is part of the Spring Boot application
lifecycle and is used for executing custom code after the Spring application context has been
fully initialized and before the application starts running. It allows you to perform complex
initialization tasks or execute code that should run just before your application starts serving
requests. ApplicationRunner wraps the raw application arguments and exposes the
ApplicationArguments interface, which has many convenient methods to get arguments, like
getOptionNames() to return all the arguments' names, getOptionValues() to return the
argument values, and raw source arguments with method getSourceArgs().

In Spring Boot, both CommandLineRunner and ApplicationRunner are interfaces that allow
you to execute code after the Spring application context has been fully initialized. They serve
a similar purpose but differ slightly in the way they accept and handle command-line
arguments.

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class MyRunners implements ApplicationRunner {

@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Using ApplicationRunner");
System.out.println("Non-option args: " + args.getNonOptionArgs());
System.out.println("Option names: " + args.getOptionNames());
System.out.println("Option values: " + args.getOptionValues("myOption"));
}
}

Here are the key differences between CommandLineRunner and ApplicationRunner:

Argument Handling:
CommandLineRunner: The run() method of CommandLineRunner receives an array of String
arguments (String... args). These arguments are the command-line arguments passed to the
application when it starts.

139 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


ApplicationRunner: The run() method of ApplicationRunner receives an
ApplicationArguments object. This object provides a more structured way to access and work
with command-line arguments. It includes methods for accessing arguments, option names,
and various other features.

Use Cases:
CommandLineRunner: It is suitable for simple cases where you need access to raw command-
line arguments as plain strings. For example, if you want to extract specific values or flags
from command-line arguments.
ApplicationRunner: It is more versatile and powerful when dealing with complex command-
line argument scenarios. It provides features like option values, non-option arguments, option
names, and support for argument validation. This makes it well-suited for applications with
more advanced command-line parsing requirements.

Your choice between CommandLineRunner and ApplicationRunner depends on your specific


requirements and the complexity of command-line argument processing in your Spring Boot
application. If you need advanced features like option parsing and validation,
ApplicationRunner is the more suitable choice. Otherwise, CommandLineRunner provides a
simpler, more straightforward approach.

140 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Spring Boot JDBC:

141 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Spring Boot JDBC:
Spring Boot JDBC is a part of the Spring Boot framework that simplifies the use of JDBC
(Java Database Connectivity) for database operations in your Java applications. Spring JDBC is
a framework that provides an abstraction layer on top of JDBC. This makes it easier to write
JDBC code and reduces the amount of boilerplate code that needs to be written. Spring JDBC
also provides a number of features that make it easier to manage database connections,
handle transactions, and execute queries. Spring Boot builds on top of the Spring Framework
and provides additional features and simplifications to make it easier to work with databases.
Here are some key aspects of Spring Boot JDBC:
Data Source Configuration: Spring Boot simplifies the configuration of data sources for your
application. It can automatically configure a data source for you based on the properties you
specify in the application configuration files application.properties or application.yml
Template Classes: Spring Boot includes a set of template classes, such as JdbcTemplate, that
simplify database operations. These templates provide higher-level abstractions for executing
SQL queries, managing connections, and handling exceptions.
Exception Handling: Spring Boot JDBC helps manage database-related exceptions. It
translates database-specific exceptions into more meaningful, standardized Spring
exceptions, making error handling easier and more consistent.
Connection Pooling: Connection pooling is a technique for efficiently managing database
connections. Spring Boot can configure a connection pool for your data source, helping
improve application performance by reusing existing database connections.
Transaction Management: Spring Boot simplifies transaction management in JDBC
applications. It allows you to use declarative transaction annotations or programmatic
transaction management with ease.
Here are some concepts of Spring JDBC:

DataSource: DataSource is a JDBC object that represents a connection to a database. Spring


provides a number of data source implementations, such as DriverManagerDataSource.

JdbcTemplate: The org.springframework.jdbc.core.JdbcTemplate is a central class in Spring


JDBC that simplifies database operations. It encapsulates the common JDBC operations like
executing queries, updates, and stored procedures. It handles resource management,
exception handling, and result set processing.

RowMapper: A RowMapper is an interface used to map rows from a database result set to
Java objects. It defines a method to convert a row into an object of a specific class.

Transaction management: Spring provides built-in transaction management capabilities


through declarative or programmatic approaches. You can easily define transaction
boundaries and have fine-grained control over transaction behaviour with Spring JDBC.

142 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Overall, Spring Boot JDBC is a powerful framework that can make it easier to write JDBC code.
However, it is important to be aware of the limitations of Spring JDBC before using it. Using
Spring JDBC, you can perform typical CRUD (Create, Read, Update, Delete) operations on
databases without dealing with the boilerplate code typically required in JDBC programming.

Here are some of the basic steps involved in using Spring Boot JDBC:
• Create a JdbcTemplate.
• Execute a JDBC query.

Let's see few methods of spring JdbcTemplate class.

• int update(String query) is used to insert, update and delete records.


• void execute(String query) is used to execute DDL query.
• List query(String query, RowMapper rm) is used to fetch records using RowMapper.

Similarly Spring / Spring Boot JDBC module provided many predefined classes and methods
to perform all database operations whatever we can do with JDBC API.

NOTE: Please be ready with Database table before writing JDBC logic.
Steps for Spring Boot JDBC Project:
Note: I am using Oracle Database for all examples. If you are using another database other
than Oracle, We just need to replace URL, User Name and Password of other database.
➢ Open STS and Create Project with Spring Boot Data JDBC dependency.

143 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ Select Spring Data JDBC and Oracle Driver Dependencies -> click on Finish
Oracle Driver: When developing an application that needs to interact with Oracle Database,
you typically need to include the appropriate Oracle driver as a dependency in your project.
The driver provides the necessary classes and methods for establishing connections, executing
SQL queries, and processing database results. How we added ojdbc.jar file in JDBC
programming projects. Same ojdbc.jar file here also added by Spring Boot into project level.

Now We have to start Programming.


Requirement: Add Product Details.
Create Table in Database:
CREATE TABLE PRODUCT(ID NUMBER(10), NAME VARCHAR2(50), PRICE NUMBER(10));

144 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ We have to add database details inside application.properties with help of pre-defined
properties provided by Spring Boot i.e. DataSource Configuration. Here, DataSource
configuration is controlled by external configuration properties in spring.datasource.*
Note: Spring Boot reduce the JDBC driver class for most databases from the URL. If you
need to specify a specific class, you can use the spring.datasource.driver-class-name
property.

#Oracle Database Details

spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.username=c##dilip
spring.datasource.password=dilip

➢ Create a Component class for doing Database operations. Inside class, we have to
autowire JdbcTemplate to utilize pre-defined functionalities.

package com.dilip;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class DataBaseOperations {

@Autowired
JdbcTemplate jdbcTemplate;

public void addProduct() {


jdbcTemplate.update("insert into product values(3,'TV', 25000)");
}
}

➢ Now Call above method.

package com.dilip;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class SpringBootJdbcDemoApplication {

public static void main(String[] args) {


ApplicationContext context =

145 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


SpringApplication.run(SpringBootJdbcDemoApplication.class, args);

DataBaseOperations dbOperations = context.getBean(DataBaseOperations.class);


dbOperations.addProduct();
}
}

Verify in Database: Data is inserted or not.

This is how Spring boot JDBC module simplified Database operations will very less amount of
code.
Let’s perform other database operations.
Requirement: Load all Product Details from Database as List of Product Objects.
➢ Here we have to create a POJO class of Product with properties.

package com.dilip;

import lombok.Data;

@Data
public class Product {
int id;
String name;
int price;
}

➢ Create another method inside Database Operations class.

package com.dilip;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component

146 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


public class DataBaseOperations {

@Autowired
JdbcTemplate jdbcTemplate;

public void addProduct() {


jdbcTemplate.update("insert into product values(2,'laptop', 100000)");
}

public void loadAllProducts() {

String query = "select * from product";


List<Product> allProducts =
jdbcTemplate.query(query, new BeanPropertyRowMapper<Product>(Product.class));

for (Product p : allProducts) {


System.out.println(p);
}
}
}

➢ Execute above logic.

package com.dilip;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class SpringBootJdbcDemoApplication {

public static void main(String[] args) {

ApplicationContext context =
SpringApplication.run(SpringBootJdbcDemoApplication.class, args);

DataBaseOperations dbOperations = context.getBean(DataBaseOperations.class);


dbOperations.addProduct();
dbOperations.loadAllProducts();

}
}

➢ Now verify in Console Output. All Records are loaded and converted as Lis of Product
Objects.

147 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Adding few more Requirements.

package com.dilip;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class DataBaseOperations {

@Autowired
JdbcTemplate jdbcTemplate;

public void addProduct() {


jdbcTemplate.update("insert into product values(2,'laptop', 100000)");
}

public void loadAllProducts() {


String query = "select * from product";
List<Product> allProducts =
jdbcTemplate.query(query, new BeanPropertyRowMapper<Product>(Product.class));

for (Product p : allProducts) {


System.out.println(p);
}
}

// Select all product Ids as List Object of Ids


public void getAllProductIds() {
List<Integer> allIds =
jdbcTemplate.queryForList("select id from product", Integer.class);
System.out.println(allIds);
}

//delete product by id

148 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


public void deleteProduct(int id) {
String query = "delete from product where id=" + id;
System.out.println(query);
int count = jdbcTemplate.update(query);
System.out.println("Nof of Records Deleted :" + count);
}
}

➢ Test above methods and logic now and verify in database.

package com.dilip;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class SpringBootJdbcDemoApplication {

public static void main(String[] args) {


ApplicationContext context =
SpringApplication.run(SpringBootJdbcDemoApplication.class, args);
DataBaseOperations dbOperations =
context.getBean(DataBaseOperations.class);
dbOperations.addProduct();
dbOperations.loadAllProducts();
dbOperations.getAllProductIds();
dbOperations.deleteProduct(3);
}
}

➢ Verify Console Output and inside Database record delated or not.

149 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Inside Database: Product Id with 3 is deleted.

Positional Parameters in Query :


Requirement : Update Product Details with Product Id.
Here, I am using positional parameters “?” as part of database Query to pass real values to
queries.
In this scenario, Spring JDBC provided an overloaded method update(String sql, @Nullable
Object... args). In this method, we have to pass positional parameter values in an order.

package com.dilip;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class DataBaseOperations {

@Autowired
JdbcTemplate jdbcTemplate;

public void updateProductData(int price, int id) {


String query = "update product set price=? where id=?";
jdbcTemplate.update(query, price, id);
}
}

Testing:

package com.dilip;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication

150 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


public class SpringBootJdbcDemoApplication {
public static void main(String[] args) {
ApplicationContext context
= SpringApplication.run(SpringBootJdbcDemoApplication.class, args);
DataBaseOperations dbOperations = context.getBean(DataBaseOperations.class);
dbOperations.updateProductData(60000, 3);
}
}

➢ Verify inside database Table, Table Data is updated or not.


Now Understand If we want to do same in Spring:
Steps for Spring JDBC Project:
Create a Project with Spring JDBC module Functionalities: Perform below Operations on
Student Table.
• Insert Data
• Update Data
• Select Data
• Delete Data

Table Creation : create table student(sid number(10), name varchar2(50), age number(3));
Please add Specific jar files which are required for JDBC module, as followed.
Project Structure : for jar files reference

• Please Create Configuration class for Configuring JdbcTemplate Bean Object with
DataSource Properties. So Let's start with some simple configuration of the data source.
• We are using Oracle database:
• The DriverManagerDataSource is used to contain the information about the database
such as driver class name, connection URL, username and password.

151 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


SpringJdbcConfig.java

package com.tek.teacher;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

@Configuration
@ComponentScan("com.tek.teacher")
public class SpringJdbcConfig {

@Bean
public JdbcTemplate getJdbcTemplate() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:orcl");
dataSource.setUsername("c##dilip");
dataSource.setPassword("dilip");
return new JdbcTemplate(dataSource);
}
}

• Create a POJO class of Student which should be aligned to database table columns and
data types.
Table : Student

➢ Student.java POJO class:

package com.tek.teacher;

public class Student {

// Class data members


private Integer age;
private String name;

152 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


private Integer sid;

// Setters and Getters


public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
@Override
public String toString() {
return "Student [age=" + age + ", name=" + name + ", sid=" + sid + "]";
}
}

Mapping Query Results to Java Object:

Another very useful feature is the ability to map query results to Java objects by
implementing the RowMapper interface i.e. when we execute select query’s, we will get
ResultSet Object with many records of database table. So if we want to convert every row as
a single Object then this row mapper will be used. For every row returned by the query, Spring
uses the row mapper to populate the java bean object.
A RowMapper is an interface in Spring JDBC that is used to map a row from a ResultSet
to an object. The RowMapper interface has a single method, mapRow(), which takes a
ResultSet and a row number as input and returns an object.
The mapRow() method is called for each row in the ResultSet. The RowMapper
implementation is responsible for extracting the data from the ResultSet and creating the
corresponding object. The object can be any type of object, but it is typically a POJO (Plain Old
Java Object).
StudentMapper.java

package com.tek.teacher;

153 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;

public class StudentMapper implements RowMapper<Student>{

@Override
public Student mapRow(ResultSet rs, int arg1) throws SQLException {

Student student = new Student();


student.setSid(rs.getInt("sid"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));

return student;
}
}

• Write a class to perform all DB operation i.e. execution of Database Queries based on
our requirement. As part of this class we will use Spring JdbcTemplate Object, and
methods to execute database queries.
StudentJDBCTemp.java

package com.tek.teacher;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class StudentJDBCTemp {

@Autowired
private JdbcTemplate jdbcTemplateObject;

public List<Student> listStudents() {


// Custom SQL query
String query = "select * from student";
List<Student> students = jdbcTemplateObject.query(query, new StudentMapper());
return students;
}

//@Override
public int addStudent(Student student) {

154 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


String query = "insert into student
values("+student.getSid()+",'"+student.getName()+"',"+student.getAge()+")";

System.out.println(query);
return jdbcTemplateObject.update(query);
}
}

NOTE: Instead of implementing mapper from RowMapper Interface, we can use class
BeanPropertyRowMapper to convert Result Set as List of Objects. Same being used in
previous Spring Boot example.

• Write class for testing all our functionalities.


TestApp.java

package com.tek.teacher;

import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestApp {

public static void main(String[] args) {


AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
context.scan("com.tek.*");
context.refresh();

StudentJDBCTemp template = context.getBean(StudentJDBCTemp.class);

//Insertion of Data
Student s = new Student();
s.setAge(30);
s.setName("tek");
s.setSid(2);

int count = template.addStudent(s);


System.out.println(count);

// Load all Students


List<Student> students = template.listStudents();
students.stream().forEach(System.out::println);
//students.stream().map(st -> st.getSid()).forEach(System.out::println);
}
}

155 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


So, Finally main difference between Spring and Spring Boot JDBC module is we have to write
Configuration class for getting JdbcTemplate Object. This is automated in Spring Boot JDBC
module. Except this, rest of all logic is as usual common in both.

Spring Data JPA

156 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


JPA and Spring Data JPA:
The Java Persistence API is a standard technology that lets you “map” objects to relational
databases. Spring Data JPA, part of the larger Spring Data family, makes it easy to easily
implement JPA based repositories. This module deals with enhanced support for JPA based
data access layers. It makes it easier to build Spring-powered applications that use data access
technologies. Too much boilerplate code has to be written to execute simple queries. As a
developer you write your repository interfaces, including custom finder methods, and Spring
will provide the implementation automatically.

• Spring Data JPA is not a JPA provider. It is a library/framework that adds an extra layer of
abstraction on top of our JPA provider (like Hibernate).
• Spring Data JPA uses Hibernate as a default JPA provider.
The spring-boot-starter-data-jpa POM provides a quick way to get started. It provides the
following key dependencies.
o Hibernate: One of the most popular JPA implementations.
o Spring Data JPA: Helps you to implement JPA-based repositories.
o Spring ORM: Core ORM support from the Spring Framework.
Java/Jakarta Persistence API (JPA) :
The Java/Jakarta Persistence API (JPA) is a specification of Java. It is used to persist data
between Java object and relational database. JPA acts as a bridge between object-oriented
domain models and relational database systems. As JPA is just a specification, it doesn't
perform any operation by itself. It requires an implementation. So, ORM tools like Hibernate,
TopLink and iBatis implements JPA specifications for data persistence. JPA represents how to
define POJO (Plain Old Java Object) as an entity and manage it with relations using some meta
configurations. They are defined either by annotations or by XML files.
Features:

• Idiomatic persistence : It enables you to write the persistence classes using object
oriented classes.
• High Performance : It has many fetching techniques and hopeful locking techniques.
• Reliable : It is highly stable and eminent. Used by many industrial programmers.

157 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


ORM(Object-Relational Mapping))
ORM(Object-Relational Mapping) is the method of querying and manipulating data
from a database using an object-oriented paradigm/programming language. By using this
method, we are able to interact with a relational database without having to use SQL. Object
Relational Mapping (ORM) is a functionality which is used to develop and maintain a
relationship between an object and relational database by mapping an object state to
database column. It is capable to handle various database operations easily such as inserting,
updating, deleting etc.
We are going to implement Entity classes to map with Database Tables.

What is Entity Class?

Entities in JPA are nothing but POJOs representing data that can be persisted in the
database. a class of type Entity indicates a class that, at an abstract level, is correlated with a
table in the database. An entity represents a table stored in a database. Every instance of an
entity represents a row in the table.

We will define POJOs with JPA annotations aligned to DB tables. We will see all annotations
with an example.

O
Relational Database Tables
R
JAVA column column

Objects M column
column
column
column

(Object
Relational
Mapping)

Annotations Used In Entity Class:

➢ @Table, @Id, @Column Annotations are used in @Entity class to represent database
table details, name is an attribute.
➢ Inside @Table, name value should be Database table name.
➢ Inside @Column, name value should be table column name.

158 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@Entity Annotation: In Java Persistence API (JPA), the @Entity annotation is used to declare
a class as an entity class. An entity class represents an object that can be stored in a database
table. In JPA, entity classes are used to map Java objects to database tables, allowing you to
perform CRUD (Create, Read, Update, Delete) operations on those objects in a relational
database.

Here's how we use the @Entity annotation in JPA.

@Entity
public class Product {
//Properties
}

Entity classes in JPA represent the structure of your database tables and serve as the
foundation for database operations using JPA. You can create, retrieve, update, and delete
instances of these entity classes, and the changes will be reflected in the corresponding
database tables, making it a powerful tool for working with relational databases in Java
applications.

@Table Annotation: In Java Persistence API (JPA), the @Table annotation is used to specify
the details of the database table that corresponds to an @Entity class. When we create an
entity class, we want to map it to a specific table in the database. The @Table annotation
allows you to define various attributes related to the database table.

Here's how we use the @Table annotation in JPA.

@Entity
@Table(name = "products")
public class Product {
//properties
}

@Table(name="products") , Specifies that this entity is associated with a table named


"products" in the database. You can provide the `name` attribute to specify the name of the
table. If you don't provide the `name` attribute, JPA will use the default table name, which is
often derived from the name of the entity class (in this case, "Product").

We can also use other attributes of the `@Table` annotation to specify additional information
about the table, such as the schema, unique constraints, indexes, and more, depending on
your database and application requirements.

@Id Annotation: In Java Persistence API (JPA), `@Id` is an annotation used to declare a field
or property as the primary key of an entity class. JPA is a Java specification for object-
relational mapping (ORM), which allows you to map Java objects to database tables. The @Id
annotation is an essential part of defining the structure of your entity classes when working
with JPA. Here's how you use @Id in JPA.

159 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Field-Level Annotation: We can place @Id annotation directly on a field in our entity class.
Property-Level Annotation: We can also place the @Id annotation on a getter method if
you prefer property access instead of field access.

@Entity
@Table(name = "products")
public class Product {
private Long id;

@Id
public Long getId() {
return id;
}
}

The @Id annotation marks the specified field or property as the primary key for the associated
entity. This means that the value of this field uniquely identifies each row in the corresponding
database table. Additionally, you may need to specify how the primary key is generated, such
as using database-generated values or providing your own. JPA provides various strategies for
generating primary keys, and you can use annotations like @GeneratedValue in conjunction
with @Id to define the strategy for generating primary key values.

@Id, The field or property to which the Id annotation is applied should be one of the following
types: any Java primitive type; any primitive wrapper type; String; java.util.Date;
java.sql.Date; java.math.BigDecimal; java.math.BigInteger. The mapped column for the
primary key of the entity is assumed to be the primary key of the primary table.

@Column Annotation: In Java Persistence API (JPA), the @Column annotation is used to
specify the details of a database column that corresponds to a field or property of an entity
class. When you create an entity class, you often want to map its fields or properties to
specific columns in the associated database table. The @Column annotation allows you to
define various attributes related to the database column.

Here's how you use the @Column annotation in JPA:

@Entity
@Table(name = "products")
public class Product {

@Id
@Column
private Long id;

@Column(name = "product_name", length = 100, nullable = false)


private String name;

160 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@Column(name = "product_price", precision = 10, scale = 2)
private BigDecimal price;

// Constructors, getters, setters, and other methods...


}

@Column(name = "product_name", length = 100, nullable = false): The @Column


annotation is used to specify the mapping of entity class fields to table columns. In this
example, it indicates that the “name” field should be mapped to a column named
"product_name" in the database table. Additional attributes like length and nullable specify
constraints on the column:

• name: Specifies the name of the database column. If you don't provide the `name`
attribute, JPA will use the field or property name as the default column name.
• length: Specifies the maximum length of the column's value.
• nullable: Indicates whether the column can contain null values. Setting it to false means
the column is mandatory (cannot be null).

@Column(name = "product_price", precision = 10, scale = 2): Similarly, this annotation


specifies the mapping for the `price` field, including the column name and precision/scale for
numeric values.

The @Column annotation provides a way to customize the mapping between your entity class
fields or properties and database columns. You can use it to specify various attributes like
column name, data type, length, and more, depending on your database and application
requirements.

➢ Create Spring Boot application with JPA dependency and respective Database Driver.

161 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ Here we are working with Database, So please Add Database Details like URL, username
and password inside application.properties file.

application.properties:

spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.username=c##dilip
spring.datasource.password=dilip

➢ Create Entity Class:

First we should have Database table details with us, Based on Table Details we are
creating a POJO class i.e. configuring Table and column details along with POJO class
Properties. I have a table in my database as following. Then I will create POJO class by creating
Properties aligned to DB table datatypes and column names with help of JPA annotations.

Table Name : flipkart_orders

Table : FLIPKART_ORDERS JAVA Entity Class : FlipakartOrder


ORDERID NUMBER(10) orderID long
PRODUCTNAME VARCHAR2(50) productName String
TOTALAMOUNT NUMBER(10,2) totalAmount float

Entity Class: FlipakartOrder.java

package com.flipkart.dao;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;

@Entity
@Table(name = "FLIPKART_ORDERS")
public class FlipakartOrder {

@Id
@Column(name = "ORDERID")
private long orderID;

@Column(name = "PRODUCTNAME")
private String productName;

@Column(name = "TOTALAMOUNT")
private float totalAmount;

162 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


public long getOrderID() {
return orderID;
}
public void setOrderID(long orderID) {
this.orderID = orderID;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public float getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(float totalAmount) {
this.totalAmount = totalAmount;
}
}

Note: When Database Table column name and Entity class property name are equal, it’s not
mandatory to use @Column annotation i.e. It’s an Optional in such case. If both are different
then we should use @Column annotation along with value.

For Example : Assume, we written property and column as below in an Entity class.

@Column(name="pincode")
private int pincode;

In this case we can define only property name i.e. internally JPA considers pincode is aligned
with pincode column in table

private int pincode;

Spring JPA Repositories:

Spring Data JPA repositories are interfaces that you can define to access data. JPA
queries are created automatically from your method names. In Spring Data JPA, a repository
is an abstraction that provides an interface to interact with a database using Java Persistence
API (JPA). Spring Data JPA repositories offer a set of common methods for performing CRUD
(Create, Read, Update, Delete) operations on database entities without requiring you to write
boilerplate code. These repositories also allow you to define custom queries using method
names, saving you from writing complex SQL queries manually.

163 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Spring JPA Provided 2 Types of Repositories
▪ JpaRepository
▪ CrudRepository

Repositories work in Spring JPA by extending the JpaRepository/CrudRepository


interface. These interfaces provides a number of default methods for performing CRUD
operations, such as save, findById, and delete etc.. we can also extend the JpaRepository
interface to add your own custom methods.

When we create a repository, Spring Data JPA will automatically create an


implementation for it. This implementation will use the JPA provider that you have
configured in your Spring application.

Create Spring JPA Repository:

package com.flipkart.dao;

import org.springframework.data.jpa.repository.JpaRepository;

public interface FlipakartOrderRepository extends JpaRepository< FlipakartOrder, Long> {

This repository is for a FlipakartOrder entity. The Long parameter in the extends
JpaRepository statement specifies the type of the entity's identifier representing primary key
column in Table.

The FlipakartOrderRepository interface provides a number of default methods for


performing CRUD operations on FlipakartOrder entities. For example, the save() method can
be used to save a new FlipakartOrder entity, and the findById() method can be used to find
a FlipakartOrder entity by its identifier.

We can also extend the FlipakartOrderRepository interface to add your own custom
methods. For example, you could add a method to find all FlipakartOrder entities that based
on a Product name.

Benefits of using Spring JPA Repositories:

➢ Reduced boilerplate code: Repositories provide a number of default methods for


performing CRUD operations, so you don't have to write as much code and SQL Queries.
➢ Enhanced flexibility: Repositories allow you to add your own custom methods, so you can
tailor your data access code to your specific requirements.
Note: If We are using JPA in your Spring application, highly recommended using Spring JPA
Repositories. They will make your code simpler, more consistent, and more flexible.

164 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Here's how repositories work in Spring Data JPA:

➢ Define an Entity Class: An entity class is a Java class that represents a database table. It is
annotated with @Entity and contains fields that map to table columns.
➢ Create a Repository Interface: Create an interface that extends the JpaRepository
interface provided by Spring Data JPA. This interface will be used to perform database
operations on the associated entity. You can also extend other repository interfaces such
as PagingAndSortingRepository, CrudRepository, etc., based on your needs.
➢ Method Naming Conventions: Spring Data JPA automatically generates queries based on
the method names defined in the repository interface. For example, a method named
findByFirstName will generate a query to retrieve records based on the first name.
➢ Custom Queries: You can define custom query methods by using specific keywords in the
method name, such as find...By..., read...By..., query...By..., or get...By.... Additionally, you
can use @Query annotations to write JPQL (Java Persistence Query Language) or native
SQL queries.
➢ Dependency Injection: Inject the repository interface into your service or controller
classes using Spring's dependency injection.
➢ Use Repository Methods: You can now use the methods defined in the repository
interface to perform database operations.
Spring Data JPA handles the underlying database interactions, such as generating SQL queries,
executing them, and mapping the results back to Java objects.
Now create a Component class For Performing Database operations as per Requirements
Requirement: Add One Order Details to our database table "FLIPKART_ORDERS"

The save() method of Spring JPA Repository, can be used to both insert a new entity or update
an existing one if an ID is provided.

package com.flipkart.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

// To Execute/Perform DB operations
@Component
public class OrderDbOperations {

@Autowired
FlipakartOrderRepository flipakartOrderRepository;

public void addOrderDetaisl(FlipakartOrder order) {


flipakartOrderRepository.save(order);
}
}

165 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ Now Inside Spring Boot Application Main method class, get the OrderDbOperations
instance and call methods.

package com.flipkart;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.flipkart.dao.FlipakartOrder;
import com.flipkart.dao.OrderDbOperations;

@SpringBootApplication
public class SpringBootJpaDemoApplication {
public static void main(String[] args) {
ApplicationContext context
= SpringApplication.run(SpringBootJpaDemoApplication.class, args);

// Created Entity Object


FlipakartOrder order = new FlipakartOrder();
order.setOrderID(9988);
order.setProductName("Book");
order.setTotalAmount(333.00f);

// Pass Entity Object to Repository Method


OrderDbOperations dbOperation
= context.getBean(OrderDbOperations.class);
dbOperation.addOrderDetaisl(order);
}
}

Project Structure:

Testing: Now Execute The Programme. If No errors/exceptions verify Inside Database table,
Data inserted or not.

166 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Based on Repository method save() of flipakartOrderRepository.save(order), JPA internally
generates implementation code as well as SQL queries and then those Queries will be
executed on database.

NOTE: In our example, we are nowhere written any SQL query to do Database operation.

Similarly, we have many predefined methods of Spring repository to do CRUD operations.

We learned how to configure the persistence layer of a Spring application that uses Spring
Data JPA and Hibernate. Let’s create few more examples to do CRUD operations on
Database tables.

Internally, Spring JPA/Hibernate Generates SQL query based on repository methods which we
are using in our logic i.e. Spring JPA Internally generates implementation for our Repository
Interface like FlipakartOrderRepository and injects instance of that implementation inside
Repository.

spring.jpa.show-sql: The spring.jpa.show-sql property is a spring JPA configuration


property that controls whether or not Hibernate will log the SQL statements that it generates.
The possible values for this property are:

true: Hibernate will log all SQL statements to the console.


false: Hibernate will not log any SQL statements.

The default value for this property is false. This means that Hibernate will not log any SQL
statements by default. If you want to see the SQL statements that Hibernate is generating,
you will need to set this property to true.

Logging SQL statements can be useful for debugging purposes. If you are having problems
with your application, you can enable logging and see what SQL statements Hibernate is
generating. This can help you to identify the source of the problem.

Add below Property In : application.properties

spring.jpa.show-sql=true

167 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Requirement: Add List of Orders at time to the table.

➢ saveAll(): This method will be used for persisting all objects into table.

Add Logic in : OrderDbOperations.java

package com.flipkart.dao;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

// To Execute/Perform DB operations
@Component
public class OrderDbOperations {

@Autowired
FlipakartOrderRepository flipakartOrderRepository;

//Adding List Of Orders ata time


public void addListOfOrders() {

List<FlipakartOrder> orders = new ArrayList<>();

FlipakartOrder order1 = new FlipakartOrder();


order1.setOrderID(123);
order1.setProductName("Keyboard");
order1.setTotalAmount(500.00f);

FlipakartOrder order2 = new FlipakartOrder();


order2.setOrderID(124);
order2.setProductName("Mouse");
order2.setTotalAmount(300.00f);

FlipakartOrder order3 = new FlipakartOrder();


order3.setOrderID(125);
order3.setProductName("Monitor");
order3.setTotalAmount(10000.00f);

orders.add(order1);
orders.add(order2);
orders.add(order3);

flipakartOrderRepository.saveAll(orders);
}
}

168 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ Execute above logic.

package com.flipkart;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.flipkart.dao.OrderDbOperations;

@SpringBootApplication
public class SpringBootJpaDemoApplication {
public static void main(String[] args) {
ApplicationContext context =
SpringApplication.run(SpringBootJpaDemoApplication.class, args);

OrderDbOperations dbOperation = context.getBean(OrderDbOperations.class);


dbOperation.addListOfOrders();
}
}

➢ Now Three records will be inserted in database.

Now in application console logs, we can see SQL Queries are executed internally by JPA.

169 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Requirement: Load all Order Details from database as a List of Orders Object.

findAll(): This method will load all records of a table and converts all records as Entity Objects
and all Objects added to ArrayList i.e. finally returns List object of FlipakartOrder entity
objects.

public void loadAllOrders() {


List<FlipakartOrder> allOrders = flipakartOrderRepository.findAll();
for(FlipakartOrder order : allOrders) {
System.out.println(order.getOrderID());
System.out.println(order.getProductName());
System.out.println(order.getTotalAmount());
}
}

Please execute above logic by calling loadAllOrders().

➢ New Requirement : Let’s Have Patient Information as follows.


• Name
• Age
• Gender
• Contact Number
• Email Id

1. Add Single Patient Details


2. Add More Than One Patient Details
3. Update Patient Details
4. Select Single Patient Details
5. Select More Patient Details
6. Delete Patient Details

1. Create Spring Boot Project with JPA and Oracle Driver

170 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


2. Now Add Database Details in application.properties

#database details
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.username=c##dilip
spring.datasource.password=dilip

#to print SQL Queries


spring.jpa.show-sql=true

#DDL property
spring.jpa.hibernate.ddl-auto=update

spring.jpa.hibernate.ddl-auto: The spring.jpa.hibernate.ddl-auto property is used to


configure the automatic schema/tables generation and management behaviour of Hibernate.
This property allows you to control how Hibernate handles the database schema/tables based
on your entity classes i.e. When we created Entity Classes

Here are the possible values for the spring.jpa.hibernate.ddl-auto property:

1. none: No action is performed. The schema will not be generated.


2. validate: The database schema will be validated using the entity mappings. This means
that Hibernate will check to see if the database schema matches the entity mappings. If
there are any differences, Hibernate will throw an exception.
3. update: The database schema will be updated by comparing the existing database schema
with the entity mappings. This means that Hibernate will create or modify tables in the
database as needed to match the entity mappings.
4. create: The database schema will be created. This means that Hibernate will create all of
the tables needed for the entity mappings.
5. create-drop: The database schema will be created and then dropped when the
SessionFactory is closed. This means that Hibernate will create all of the tables needed for
the entity mappings, and then drop them when the SessionFactory is closed.
3. Create Entity Class

NOTE : Configured spring.jpa.hibernate.ddl-auto value as update. So Table Creation will be


done by JPA internally if tables are not available.

package com.dilip.dao;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;

171 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@Data
@Entity
@Table
public class Patient {
@Id
@Column
private String emailId;

@Column
private String name;

@Column
private int age;

@Column
private String gender;

@Column
private String contact;
}

4. Create A JPA Repository Now : PatientRepository.java

package com.dilip.dao;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;

@Component
public interface PatientRepository extends CrudRepository<Patient, String> {

5. Create a class for DB operations : PatientOperations.java

package com.dilip.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class PatientOperations {

@Autowired
PatientRepository repository;

172 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Spring JPA Repositories Provided many predefined abstract methods for all DB CURD
operations. We should recognize those as per our DB operation.

Requirement : Add Single Patient Details


Here, we are adding Patient details means at Database level this is insert Query Operation.

save() : Used for insertion of Details. We should pass Entity Object.

Add Below Method in PatientOperations.java:

public void addPatient(Patient p) {


repository.save(p);
}

Now Test it : From Main Class : PatientApplication.java

package com.dilip;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.dilip.dao.Patient;
import com.dilip.dao.PatientOperations;

@SpringBootApplication
public class PatientApplication {

public static void main(String[] args) {


ApplicationContext context
= SpringApplication.run(PatientApplication.class, args);
PatientOperations ops = context.getBean(PatientOperations.class);

// Add Single Patient


Patient p = new Patient();
p.setEmailId("one@gmail.com");
p.setName("One Singh");
p.setContact("+918826111377");
p.setAge(30);
p.setGender("MALE");

ops.addPatient(p);
}
}

Now Execute It. Table also created by Spring Boot JPA module and One Record is inserted.

173 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Requirement : Update Patient Details

In Spring Data JPA, the save() method is commonly used for both insert and update
operations. When you call the save() method on a repository, Spring Data JPA checks whether
the entity you're trying to save already exists in the database. If it does, it updates the existing
entity; otherwise, it inserts a new entity.

So that is the reason we are seeing a select query execution before inserting data in
previous example. After select query execution with primary key column JPA checks row
count and if it is 1, then JPA will convert entity as insert operation. If count is 0 , then Spring
JPA will convert entity as update operation specific to Primary key.

Using the save() method for updates is a common and convenient approach, especially when
we want to leverage Spring Data JPA's automatic change tracking and transaction
management.

Requirement: Please update name as Dilip Singh for email id: one@gmail.com

174 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Add Below Method in PatientOperations.java:

public void updatePateinData(Patient p) {


repository.save(p);
}

Now Test it from Main class: In below if we observe, first select query executed by JPA as per
our entity Object, JPA found data so JPA decided for update Query execution. We have to
send updated data as part of Entity Object.

package com.dilip;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.dilip.dao.Patient;
import com.dilip.dao.PatientOperations;

@SpringBootApplication
public class PatientApplication {

public static void main(String[] args) {


ApplicationContext context
= SpringApplication.run(PatientApplication.class, args);
PatientOperations ops = context.getBean(PatientOperations.class);
// Update Existing Patient
Patient p = new Patient();
p.setEmailId("one@gmail.com");
p.setName("Dilip Singh");
p.setContact("+918826111377");
p.setAge(30);
p.setGender("MALE");
ops.addPatient(p);
}
}

Verify In DB :

175 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Requirement: Delete Patient Details : Deleting Patient Details based on Email ID.

Spring JPA provided a predefined method deleteById() for primary key columns delete
operations.

deleteById(): The deleteById() method in Spring Data JPA is used to remove an entity from
the database based on its primary key (ID). It's provided by the JpaRepository interface and
allows you to delete a single entity by its unique identifier.

Here's how you can use the deleteById() method in a Spring Data JPA repository:

Add Below Method in PatientOperations.java:

package com.dilip.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class PatientOperations {

@Autowired
PatientRepository repository;

public void addPatient(Patient p) {


repository.save(p);
}
public void deletePatient(String email) {
repository.deleteById(email);
}
}

Testing from Main Class:

package com.dilip;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.dilip.dao.PatientOperations;

@SpringBootApplication
public class PatientApplication {

public static void main(String[] args) {


ApplicationContext context = SpringApplication.run(PatientApplication.class, args);
PatientOperations ops = context.getBean(PatientOperations.class);

176 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


// Delete Existing Patient by email Id
ops.deletePatient("two@gmail.com");
}
}

Before Execution/Deletion:

After Execution/Deletion:

Requirement: Get Patient Details Based on Email Id.

Here Email Id is Primary key Column in table. Finding Details based on Primary key
column name Spring JPA provided a method findById().

findById(): The findById() method is used to retrieve an entity by its primary key or ID from
a relational database. Here's how you can use the findById() method in JPA.

Add Below Method in PatientOperations.java:

package com.dilip.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class PatientOperations {

@Autowired
PatientRepository repository;

177 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


public void addPatient(Patient p) {
repository.save(p);
}
public void deletePatient(String email) {
repository.deleteById(email);
}
public Patient fetchByEmailId(String emailId) {
return repository.findById(emailId).get();
}
}

Testing from Main Class:

package com.dilip;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.dilip.dao.Patient;
import com.dilip.dao.PatientOperations;

@SpringBootApplication
public class PatientApplication {

public static void main(String[] args) {


ApplicationContext context = SpringApplication.run(PatientApplication.class, args);
PatientOperations ops = context.getBean(PatientOperations.class);
// Fetch Patient Details By Email ID
Patient patient = ops.fetchByEmailId("one@gmail.com");
System.out.println(patient);
}
}

Output in Console:

Similarly Spring JPA provided many useful and predefined methods inside JPA
repositories to perform CRUD Operations.

For example :
findAll() : for retrieve all Records From Table

178 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


deleteAll(): for deleting all Records From Table
etc..
For Non Primary Key columns of Table or Entity, Spring JPA provided Custom Query
Repository Methods. Let’s Explore.

Spring Data JPA Custom Query Repository Methods:

Spring Data JPA allows you to define custom repository methods by simply declaring
method signature with entity class property Name which is aligned with Database column.
The method name must start with findBy, getBy, queryBy, countBy, or readBy. The findBy is
mostly used by the developer.

For Example: Below query methods are valid and gives same result like Patient name
matching data from Database.

public List<Patient> findByName(String name);


public List<Patient> getByName(String name);
public List<Patient> queryByName(String name);
public List<Patient> countByName(String name);
public List<Patient> readByName(String name);

➢ Patient: Name of Entity class.


➢ Name: Property name of Entity.

Rule: After findBy, The first character of Entity class field name should Upper case letter.
Although if we write the first character of the field in lower case then it will work but we
should use camelCase for the method names. Equal Number of Method Parameters should
be defined in abstract method.

Requirement: Get Details of Patients by Age i.e. Single Column.


Result we will get More than One record i.e. List of Entity Objects. So return type is
List<Patient>

Step 1: Create a Custom method inside Repository

package com.dilip.repository;

import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;
import com.dilip.entity.Patient;

@Component
public interface PatientRepository extends CrudRepository<Patient, String> {
List<Patient> findByAge(int age);
}

179 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Step 2: Now call Above Method inside Db operations to pass Age value.

package com.dilip.operations;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.dilip.entity.Patient;
import com.dilip.repository.PatientRepository;

@Component
public class PatientOperations {

@Autowired
PatientRepository repository;

// Non- primary Key column


public List<Patient> fetchByAge(int age) {
return repository.findByAge(age);
}
}

Step 3: Now Test It from Main Class.

package com.dilip;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.dilip.dao.Patient;
import com.dilip.dao.PatientOperations;

@SpringBootApplication
public class PatientApplication {
public static void main(String[] args) {

ApplicationContext context = SpringApplication.run(PatientApplication.class, args);


PatientOperations ops = context.getBean(PatientOperations.class);
//Fetch Patient Details By Age
List<Patient> patients = ops.fetchByAge(31);
System.out.println(patients);
}
}

Output: In Below, Query generated by JPA and Executed. Got Two Entity Objects In Side List .

180 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Similar to Age, we can fetch data with other columns as well by defining custom Query
methods.

Fetching Data with Multiple Columns:


Rule: We can write the query method using multiple fields using predefined keywords(eg.
And, Or etc) but these keywords are case sensitive. We must use “And” instead of “and”.

Requirement: Fetch Data with Age and Gender Columns.


• Age is 28
• Gender is Female

Step 1: Create a Custom method inside Repository.

Method should have 2 parameters age and gender in this case because we are getting data
with 2 properties.

package com.dilip.repository;

import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;
import com.dilip.entity.Patient;

@Component
public interface PatientRepository extends CrudRepository<Patient, String> {
List<Patient> findByAgeAndGender(int age, String gender);
}

Step 2: Now call Above Method inside Db operations to pass Age and gender values.

package com.dilip.operations;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.dilip.entity.Patient;
import com.dilip.repository.PatientRepository;

@Component
public class PatientOperations {

181 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@Autowired
PatientRepository repository;

// based on Age + Gender


public List<Patient> getPateintsWithAgeAndGender(int age, String gender) {
return repository.findByAgeAndGender(age, gender);
}
}

Step 3: Now Test It from Main Class.

package com.dilip;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import java.util.List;
import com.dilip.dao.Patient;
import com.dilip.dao.PatientOperations;

@SpringBootApplication
public class PatientApplication {
public static void main(String[] args) {
ApplicationContext context
= SpringApplication.run(PatientApplication.class, args);
PatientOperations ops = context.getBean(PatientOperations.class);

//Fetch Patient Details By Age and Gender


List<Patient> patients = ops.getPateintsWithAgeAndGender(28,"FEMALE");
System.out.println(patients);
}
}

Table Data:

182 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Expected Output:

We can write the query method if we want to restrict the number of records by directly
providing the number as the digit in method name. We need to add the First or the Top
keywords before the By and after find.

public List<Student> findFirst3ByName(String name);


public List<Student> findTop3ByName(String name);

Both query methods will return only first 3 records.

Similar to these examples and operations we can perform multiple Database operations
however we will do in SQL operations.

List of keywords used to write custom repository methods:

And, Or, Is, Equals, Between, LessThan, LessThanEqual, GreaterThan, GreaterThanEqual,


After, Before, IsNull, IsNotNull, NotNull, Like, NotLike, StartingWith, EndingWith, Containing,
OrderBy, Not, In, NotIn, True, False, IgnoreCase.

Some of the examples for Method Names formations:

public List<Student> findFirst3ByName(String name);


public List<Student> findByNameIs(String name);
public List<Student> findByNameEquals(String name);
public List<Student> findByRollNumber(String rollNumber);
public List<Student> findByUniversity(String university);
public List<Student> findByNameAndRollNumber(String name, String rollNumber);
public List<Student> findByRollNumberIn(List<String> rollNumbers);
public List<Student> findByRollNumberNotIn(List<String> rollNumbers);
public List<Student> findByRollNumberBetween(String start, String end);
public List<Student> findByNameNot(String name);
public List<Student> findByNameContainingIgnoreCase(String name);
public List<Student> findByNameLike(String name);
public List<Student> findByRollNumberGreaterThan(String rollnumber);
public List<Student> findByRollNumberLessThan(String rollnumber);

183 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@GeneratedValue Annotation:

In Java Persistence API (JPA), the @GeneratedValue annotation is used to specify how
primary key values for database entities should be generated. This annotation is typically used
in conjunction with the @Id annotation, which marks a field or property as the primary key of
an entity class. The @GeneratedValue annotation provides options for automatically
generating primary key values when inserting records into a database table.

When you annotate a field with @GeneratedValue, you’re telling Spring Boot to automatically
generate unique values for that field.

Here are some of the key attributes of the @GeneratedValue annotation:

strategy:
This attribute specifies the generation strategy for primary key values. This is used to
specify how to auto-generate the field values. There are five possible values for the strategy
element on the GeneratedValue annotation: IDENTITY, AUTO, TABLE, SEQUENCE and UUID.
These five values are available in the enum, GeneratorType.

1. GenerationType.AUTO: This is the default strategy. The JPA provider selects the most
appropriate strategy based on the database and its capabilities. Assign the field a
generated value, leaving the details to the JPA vendor. Tells JPA to pick the strategy that
is preferred by the used database platform.

The preferred strategies are IDENTITY for MySQL, SQLite and MsSQL and SEQUENCE for
Oracle and PostgreSQL. This strategy provides full portability.

2. GenerationType.IDENTITY: The primary key value is generated by the database system


itself (e.g., auto-increment in MySQL or identity columns in SQL Server, SERIAL in
PostgreSQL).

3. GenerationType.SEQUENCE: The primary key value is generated using a database


sequence. Tells JPA to use a database sequence for ID generation. This strategy does
currently not provide full portability. Sequences are supported by Oracle and PostgreSql.
When this value is used then generator filed is mandatory to specify the generator.

4. GenerationType.TABLE: The primary key value is generated using a database table to


maintain unique key values. Tells JPA to use a separate table for ID generation. This
strategy provides full portability. When this value is used then generator filed is
mandatory to specify the generator.

5. GenerationType.UUID: Jakarta EE 10 now adds the GenerationType for a UUID, so that we


can use Universally Unique Identifiers (UUIDs) as the primary key values. Using the
GenerationType.UUID strategy, This is the easiest way to generate UUID values. Simply
annotate the primary key field with the @GeneratedValue annotation and set the

184 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


strategy attribute to GenerationType.UUID. The persistence provider will automatically
generate a UUID value for the primary key column.
NOTE: Here We are working with Oracle Database. Sometimes Different Databases will
exhibit different functionalities w.r.to different Generated Strategies.
Examples For All Strategies:
GenerationType.AUTO:

In JPA, the GenerationType.AUTO strategy is the default strategy for generating primary
key values. It instructs the persistence provider to choose the most appropriate strategy for
generating primary key values based on the underlying database and configuration. This
typically maps to either GenerationType.IDENTITY or GenerationType.SEQUENCE,
depending on database capabilities.

When to Use GenerationType.AUTO?


The GenerationType.AUTO strategy is a convenient choice for most applications because
it eliminates the need to explicitly specify a generation strategy of primary key values. It is
particularly useful when you are using a database that supports both
GenerationType.IDENTITY and GenerationType.SEQUENCE, as the persistence provider will
automatically select the most efficient strategy for your database.

However, there are some cases where we may want to explicitly specify a generation
strategy. For example, if you need to ensure that primary key values are generated
sequentially, you should use the GenerationType.SEQUENCE strategy. Or, if you need to use
a custom generator, you should specify the name of the generator using the generator
attribute of the @GeneratedValue annotation.

Benefits of GenerationType.AUTO
➢ Convenience: It eliminates the need to explicitly specify a generation strategy.
➢ Automatic selection: It selects the most appropriate strategy for the underlying database.
➢ Compatibility: It is compatible with a wide range of databases.

Limitations of GenerationType.AUTO

➢ Lack of control: It may not be the most efficient strategy for all databases.
➢ Potential for performance issues: If the persistence provider selects the wrong
strategy, it could lead to performance issues.

Overall, the GenerationType.AUTO strategy is a good default choice for generating


primary key values in JPA applications. However, you should be aware of its limitations and
consider explicitly specifying a generation strategy if you have specific requirements.

185 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ Create Spring Boot Data JPA project

➢ Now Add Database and JPA properties in application.properties file:

#database details
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.username=c##dilip
spring.datasource.password=dilip

#to print SQL Queries


spring.jpa.show-sql=true

#DDL property
spring.jpa.hibernate.ddl-auto=update

➢ Now Create An Entity class with @GeneratedValue column : Patient.java

package com.tek.teacher.data;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

186 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@Entity
@Table(name = "patient_details")
public class Patient {

@Id
@Column(name = "patient_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private long pateintId;

@Column(name = "patient_name")
private String name;

@Column(name = "patient_age")
private int age;

public long getPateintId() {


return pateintId;
}
public void setPateintId(long pateintId) {
this.pateintId = pateintId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

➢ Now Try to Persist Data with above entity class. Create a Repository.

package com.tek.teacher.data;

import org.springframework.data.jpa.repository.JpaRepository;

public interface PatientRepository extends JpaRepository<Patient, Long> {

187 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ Now Create Entity Object and try to execute. Here we are not passing pateintId value
to Entity Object.

package com.tek.teacher.data;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class PatientOperations {

@Autowired
PatientRepository repository;

public void addPatient() {


Patient patient = new Patient();
patient.setAge(44);
patient.setName("naresh Singh");
repository.save(patient);
}
}

➢ Call/Execute above method for persisting data.

package com.tek.teacher;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.tek.teacher.data.PatientOperations;

@SpringBootApplication
public class SpringBootJpaGeneartedvalueApplication {

public static void main(String[] args) {


ApplicationContext context =
SpringApplication.run(SpringBootJpaGeneartedvalueApplication.class, args);

PatientOperations ops = context.getBean(PatientOperations.class);


ops.addPatient();
}
}

188 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Result : Please Observe in Console Logs, How Spring JPA created values of Primary Key
Column of Patient table.

i.e. Spring JPA created by a new sequence for the column PATIENT_ID values.

Verify Data Inside Table now.

➢ Now Whenever we are persisting data in patient_details, patient_id column values


will be inserted by executing sequence automatically.
➢ Execute Logic one more time.

Table Result :

189 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


GenerationType.IDENTITY:

This strategy will help us to generate the primary key value by the database itself using the
auto-increment or identity of column option. It relies on the database’s native support for
generating unique values.

➢ Entity class with IDENTITY Type:

package com.tek.teacher.data;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "patient_details")
public class Patient {

@Id
@Column(name = "patient_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long pateintId;

@Column(name = "patient_name")
private String name;

@Column(name = "patient_age")
private int age;

public long getPateintId() {


return pateintId;
}
public void setPateintId(long pateintId) {
this.pateintId = pateintId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}

190 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


public void setAge(int age) {
this.age = age;
}
}

➢ Now Execute Logic again to Persist Data in table.


➢ If we observe console logs JPA created table as follows

➢ For Column patient_id of table patient_details, JPA created IDENTITY column.


➢ Oracle introduced a way that allows you to define an identity column for a table, which is
similar to the AUTO_INCREMENT column in MySQL or IDENTITY column in SQL Server.
➢ i.e. If we connected to MySQL and used GenerationType.IDENTITY in JPA, then JPA will
create AUTO_INCREMENT column to generate Primary Key Values. Similarly If it is SQL
Server , then JPA will create IDENTITY column for same scenario.
➢ The identity column is very useful for the surrogate primary key column. When you insert
a new row into the identity column, Oracle auto-generates and insert a sequential value
into the column.
Table Data :

Execute Again :

191 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Table Result:

GenerationType.SEQUENCE:

GenerationType.SEQUENCE is used to specify that a database sequence should be used


for generating the primary key value of the entity.

➢ Entity class with IDENTITY Type:

package com.tek.teacher.data;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "patient_details")
public class Patient {

@Id
@Column(name = "patient_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long pateintId;

@Column(name = "patient_name")
private String name;

@Column(name = "patient_age")
private int age;

public long getPateintId() {


return pateintId;

192 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}
public void setPateintId(long pateintId) {
this.pateintId = pateintId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

➢ Now Execute Logic to Persist Data in table.


➢ If we observe console logs JPA created table as follows

➢ JPA created a Sequence to generate unique values. By executing this sequence, values
are inserted into Patient table for primary key column.
➢ Now when we are persisting data inside Patient table by Entity Object, always same
sequence will be used for next value.

Table Data :

193 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ Execute Logic for saving data again inside Patient table.
➢ Primary Key column value is generated from sequence and same supplied to Entity Level.

Table Data:

This is how JPA will create a sequence when we defined @GeneratedValue(strategy =


GenerationType.IDENTITY) with @Id column of Entity class.

Question: In case, if we want to generate a custom sequence for entity primary key column
instead of default sequence created by JPA, do we have any solution?

Yes, JPA provided generator with annotation @SequenceGenerator, for creating a custom
Sequence should be created by JPA instead of default one like before example.

generator:
This is used to specify the name of the named generator. Named generators are
defined using SequenceGenerator, TableGenerator. When GenerationType.SEQUENCE and
GenerationType.TABLE are used as a strategy then we must specify the generators. Value for
this generator field should be the name of SequenceGenerator, TableGenerator.

@SequenceGenerator Annotation:

Most databases allow you to create native sequences. These are database structures that
generate sequential values. The @SequenceGenerator annotation is used to represent a
named database sequence. This annotation can be kept on class level, member
level. @SequenceGenerator annotation has the following properties:

194 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Attributes:

1. name: The generator name. This property is mandatory.


2. sequenceName: The name of the database sequence. If you do not specify the database
sequence, your vendor will choose an appropriate default.
3. initialValue: The initial sequence value.
4. allocationSize: The number of values to allocate in memory for each trip to the database.
Allocating values in memory allows the JPA runtime to avoid accessing the database for
every sequence request. This number also specifies the amount that the sequence value
is incremented each time the sequence is accessed. Defaults to 50.
5. schema: The sequence's schema. If you do not name a schema, JPA uses the default
schema for the database connection.

Example with Custom Sequence Generator:

➢ Create Entity Class With @SequenceGenerator Annotation.

package com.tek.teacher.data;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.SequenceGenerator;
import jakarta.persistence.Table;

@Entity
@Table(name = "patient_details")
public class Patient {

@Id
@Column(name = "patient_id")
@SequenceGenerator(name = "pat_id_seq", sequenceName = "patient_id_seq",
initialValue = 1000, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "pat_id_seq")
private long pateintId;

@Column(name = "patient_name")
private String name;

@Column(name = "patient_age")
private int age;

public long getPateintId() {


return pateintId;

195 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}
public void setPateintId(long pateintId) {
this.pateintId = pateintId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

Data Persisting in Table:

package com.tek.teacher.data;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class PatientOperations {

@Autowired
PatientRepository repository;

public void addPatient() {


Patient patient = new Patient();
patient.setAge(33);
patient.setName("Dilip Singh");
repository.save(patient);
}
}

➢ Now JPA created a custom sequence with details provided as part of annotation
@SequenceGenerator inside Entity class Id column.
➢ Same Sequence will be executed every time for new Primary key values of column.

196 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ From Above Console Logs, Sequence Created on database with starting value 1000 and
increment always by 1 for next value.

Table Result :

➢ Execute Logic again for Persisting Data. In Below we can see patient ID column value
started with 1000 and every time incremented with 1 value continuously.

This is how we can generate a sequence by providing details with annotation inside Entity
class.

197 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


How to Use a Sequence already created/available on database inside Entity class:

➢ Created a new Sequence inside database directly as shown in below.

➢ Now use above created Sequence with JPA entity class to generate values automatically.

JPA @TableGenerator Annotation:

@TableGenerator annotation refers to a database table which is used to store increasing


sequence values for one or more entities. This annotation can be kept on class level, member
level. @TableGenerator has the following properties:

Attributes:

1. name: The generator name. This property is mandatory.


2. table: The name of the generator table. If left unspecified, database vendor will choose a
default table.
3. schema: The named table's schema.
4. pkColumnName: The name of the primary key column in the generator table. If
unspecified, your implementation will choose a default.
5. valueColumnName: The name of the column that holds the sequence value. If
unspecified, your implementation will choose a default.
6. pkColumnValue: The primary key column value of the row in the generator table holding
this sequence value. You can use the same generator table for multiple logical sequences
by supplying different pkColumnValue s. If you do not specify a value, the implementation
will supply a default.
7. initialValue: The value of the generator's first issued number.
8. allocationSize: The number of values to allocate in memory for each trip to the database.
Allocating values in memory allows the JPA runtime to avoid accessing the database for
every sequence request.

198 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Difference between GeneratedValue and SequenceGenerator/TableGenerator:

• GeneratedValue is used only to get the generated values. The two


arguments strategy and generator are used to define how the value is gained. We can
define to use the database sequence or any database value from table which is used to
store increasing sequence values. But to specify to use database sequence or table value,
we specify the named generators to generator argument.

• SequenseGenerator/TableGenerator is used to define named generators, to map a user


defined sequence generator with your JPA session. This is used to give a name to database
sequence or database value of table or any kind of generators. This name can be now
referred by the generator argument of GeneratedValue.

<TODO : Update Programs>

Sorting and Pagination in JPA:

Sorting: Sorting is a fundamental operation in data processing that involves arranging a


collection of items or data elements in a specific order. The primary purpose of sorting is to
make it easier to search for, retrieve, and work with data. Sorting can be done in ascending
(from smallest to largest) or descending (from largest to smallest) order, depending on the
requirements.

Table and Data:

199 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Requirement: Get Details by Email Id with Sorting

➢ Create Spring Boot JPA Project with Lombok Library.


➢ Add Database Properties inside application.properties file

spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.username=c##dilip
spring.datasource.password=dilip

# to print SQL queries executed by JPA


spring.jpa.show-sql=true

➢ Create Entity Class as Per Database Table.

package com.dilip.dao;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Table(name = "amazon_orders")
public class AmazonOrders {

@Id
@Column(name="order_id")
private int orderId;

200 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@Column(name ="no_of_items")
private int noOfItems;

@Column(name = "amount")
private double amount;

@Column(name="email" )
private String email;

@Column(name="pincode")
private int pincode;

@Column(name="city")
private String city;

@Column(name="gender")
private String gender;
}

➢ Now Create A Repository.

package com.dilip.dao;

import org.springframework.data.jpa.repository.JpaRepository;

public interface AmazonOrderRepository extends JpaRepository<AmazonOrders, Integer> {

➢ Now Create a Component Class for Database Operations and Add a Method for Sorting
Data

To achieve this requirement, Spring Boot JPA provided few methods in side JpaRepository.
Inside JpaRepository, JPA provided a method findAll(…) with different Arguments.

For Sorting Data : findAll(Sort sort)

Sort: In Spring Data JPA, you can use the Sort class to specify sorting criteria for your query
results. The Sort class allows you to define sorting orders for one or more attributes of our
entity class. we can use it when working with repository methods to sort query results.

201 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Here's how you can use the Sort class in Spring Data JPA:

package com.dilip.dao;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

@Component
public class OrdersOperations {

@Autowired
AmazonOrderRepository repository;

// getting order Details in ascending order


public void loadDataByemailIdWithSorting() {
List<AmazonOrders> allOrders = repository.findAll(Sort.by("email"));
System.out.println(allOrders);
}
}

Note: we have to pass Entity class Property name as part of by(..) method, which is related to
database table column.

➢ Now Execute above Logic

package com.dilip;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.dilip.dao.OrdersOperations;

@SpringBootApplication
public class SpringBootJpaSortingPaginationApplication {

public static void main(String[] args) {

ApplicationContext context
= SpringApplication.run(SpringBootJpaSortingPaginationApplication.class, args);

OrdersOperations ops = context.getBean(OrdersOperations.class);


ops.loadDataByemailIdWithSorting();
}
}

202 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Output: Table Records are Sorted by email ID and got List of Entity Objects

AmazonOrders(orderId=3344, noOfItems=4, amount=3000.0, email=dilip@gmail.com,


pincode=500072, city=Hyderbad, gender=MALE),

AmazonOrders(orderId=3232, noOfItems=4, amount=63643.0, email=laxmi@gmail.com,


pincode=500070, city=Hyderbad, gender=FEMALE),

AmazonOrders(orderId=3323, noOfItems=4, amount=63643.0, email=laxmi@gmail.com,


pincode=500070, city=Hyderbad, gender=FEMALE),

AmazonOrders(orderId=1234, noOfItems=2, amount=4000.0, email=naresh@gmail.com,


pincode=500072, city=Hyderbad, gender=MALE),

AmazonOrders(orderId=5566, noOfItems=8, amount=6000.0, email=naresh@gmail.com,


pincode=500070, city=Hyderbad, gender=MALE),

AmazonOrders(orderId=9988, noOfItems=3, amount=44444.0, email=ramesh@gmail.com,


pincode=600088, city=Chennai, gender=MALE),

AmazonOrders(orderId=3636, noOfItems=3, amount=44444.0, email=ramesh@gmail.com,


pincode=600088, city=Chennai, gender=MALE),

AmazonOrders(orderId=8888, noOfItems=10, amount=10000.0, email=suresh@gmail.com,


pincode=600099, city=Chennai, gender=MALE)

Requirement: Get Data by sorting with property noOfItems of Descending Order.

In Spring Data JPA, you can specify the direction (ascending or descending) for sorting when
using the Sort class. The Sort class allows you to create sorting orders for one or more
attributes of our entity class. To specify the direction, you can use the Direction enum.

Here's how you can use the Direction enum in Spring Data JPA:

package com.dilip.dao;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;

@Component
public class OrdersOperations {

@Autowired
AmazonOrderRepository repository;

203 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


// getting order Details in ascending order of email
public void loadDataByemailIdWithSorting() {
List<AmazonOrders> allOrders = repository.findAll(Sort.by("email"));
System.out.println(allOrders);
}

// Get Data by sorting with property noOfItems of Descending Order


public void loadDataByNoOfItemsWithDescOrder() {
List<AmazonOrders> allOrders =
repository.findAll(Sort.by(Direction.DESC, "noOfItems"));
System.out.println(allOrders);
}
}

Output: We got Entity Objects, by following noOfItems property in Descending Order.

[
AmazonOrders(orderId=8888, noOfItems=10, amount=10000.0, email=suresh@gmail.com,
pincode=600099, city=Chennai, gender=MALE),
AmazonOrders(orderId=5566, noOfItems=8, amount=6000.0, email=naresh@gmail.com,
pincode=500070, city=Hyderbad, gender=MALE),
AmazonOrders(orderId=3232, noOfItems=4, amount=63643.0, email=laxmi@gmail.com,
pincode=500070, city=Hyderbad, gender=FEMALE),
AmazonOrders(orderId=3323, noOfItems=4, amount=63643.0, email=laxmi@gmail.com,
pincode=500070, city=Hyderbad, gender=FEMALE),
AmazonOrders(orderId=3344, noOfItems=4, amount=3000.0, email=dilip@gmail.com,
pincode=500072, city=Hyderbad, gender=MALE),
AmazonOrders(orderId=3636, noOfItems=3, amount=44444.0, email=ramesh@gmail.com,
pincode=600088, city=Chennai, gender=MALE),
AmazonOrders(orderId=9988, noOfItems=3, amount=44444.0, email=ramesh@gmail.com,
pincode=600088, city=Chennai, gender=MALE),
AmazonOrders(orderId=1234, noOfItems=2, amount=4000.0, email=naresh@gmail.com,
pincode=500072, city=Hyderbad, gender=MALE)
]

Similarly we can get table Data with Sorting Order based on any table column by using Spring
Boot JPA. We can sort data with multiple columns as well.

Example: repository.findAll(Sort.by("email","noOfItems"));

Pagination:

Pagination is a technique used in software applications to divide a large set of data or


content into smaller, manageable segments called "pages." Each page typically contains a
fixed number of items, such as records from a database, search results, or content items in a
user interface. Pagination allows users to navigate through the data or content one page at a

204 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


time, making it easier to browse, consume, and interact with large datasets or content
collections.

Key features and concepts related to pagination include:

Page Size: The number of items or records displayed on each page is referred to as the "page
size" or "items per page." Common page sizes might be 10, 20, 50, or 100 items per page. The
choice of page size depends on usability considerations and the nature of the data.

Page Number: Pagination is typically associated with a page number, starting from 1 and
incrementing as users navigate through the data. Users can move forward or backward to view
different segments of the dataset.
Navigation Controls: Pagination is usually accompanied by navigation controls, such as
"Previous" and "Next" buttons or links. These controls allow users to move between pages
easily.
Total Number of Pages: The total number of pages in the dataset is determined by dividing
the total number of items by the page size. For example, if there are 100 items and the page
size is 10, there will be 10 pages.

➢ Assume a scenario, where we have 200 Records. Each page should get 25 Records, then
page number and records are divided as shown below.

Total Records 200

Page 1 1 - 25
Page 2 26 - 50
Page 3 51 - 75
Page 4 76 - 100
Page 5 101 - 125
Page 6 126 - 150
Page 7 151 - 175
Page 8 176 - 200

Requirement: Get first set of Records by default with some size from below Table data.

205 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


In Spring Data JPA, Pageable is an interface that allows you to paginate query results easily. It
provides a way to specify the page number, the number of items per page (page size), and
optional sorting criteria for your query results. This is particularly useful when you need to
retrieve a large set of data from a database and want to split it into smaller pages.

Here's how you can use Pageable in Spring JPA:

Pageable.ofSize(int size)) : size is, number of records to be loaded.

package com.dilip.dao;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

@Component
public class OrdersOperations {

@Autowired
AmazonOrderRepository repository;

public void getFirstPageData() {


List<AmazonOrders> orders = repository.findAll(Pageable.ofSize(2)).getContent();
System.out.println(orders);
}
}

➢ Now execute above logic

package com.dilip;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

206 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


import org.springframework.context.ApplicationContext;
import com.dilip.dao.OrdersOperations;

@SpringBootApplication
public class SpringBootJpaTablesAutoCreationApplication {
public static void main(String[] args) {
ApplicationContext context
= SpringApplication.run(SpringBootJpaTablesAutoCreationApplication.class, args);
OrdersOperations ops = context.getBean(OrdersOperations.class);
ops.getFirstPageData();
}
}

Output: We got first 4 records of table.

[
AmazonOrders(orderId=3323, noOfItems=4, amount=63643.0, email=laxmi@gmail.com,
pincode=500070, city=Hyderbad, gender=FEMALE),

AmazonOrders(orderId=3232, noOfItems=4, amount=63643.0, email=laxmi@gmail.com,


pincode=500070, city=Hyderbad, gender=FEMALE),
]

Requirement: Get 2nd page of Records with some size of records i.e. 3 Records.

Here we will use PageRequest class which provides pre-defined methods, where we can
provide page Numbers and number of records.

Method: PageRequest.of(int page, int size);

207 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Note: In JPA, Page Index always Starts with 0 i.e. Page number 2 representing 1 index.

package com.dilip.dao;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

@Component
public class OrdersOperations {

@Autowired
AmazonOrderRepository repository;

public void getRecordsByPageIdAndNoOfRecords(int pageId, int noOfReorcds) {

Pageable pageable = PageRequest.of(pageId, noOfReorcds);

List<AmazonOrders> allOrders = repository.findAll(pageable).getContent();


System.out.println(allOrders);

}
}

➢ Now execute above logic

package com.dilip;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

import com.dilip.dao.OrdersOperations;

@SpringBootApplication
public class SpringBootJpaTablesAutoCreationApplication {
public static void main(String[] args) {
ApplicationContext context
= SpringApplication.run(SpringBootJpaTablesAutoCreationApplication.class, args);
OrdersOperations ops = context.getBean(OrdersOperations.class);
ops.getRecordsByPageIdAndNoOfRecords(1,3);
}
}

208 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Output: From our Table data, we got 4-6 Records which is representing 2nd Page of Data.

[
AmazonOrders(orderId=3344, noOfItems=4, amount=3000.0, email=dilip@gmail.com,
pincode=500072, city=Hyderbad, gender=MALE),

AmazonOrders(orderId=1234, noOfItems=2, amount=4000.0, email=naresh@gmail.com,


pincode=500072, city=Hyderbad, gender=MALE),

AmazonOrders(orderId=5566, noOfItems=8, amount=6000.0, email=naresh@gmail.com,


pincode=500070, city=Hyderbad, gender=MALE)
]

Requirement: Pagination with Sorting:

Get 2nd page of Records with some size of records i.e. 3 Records along with Sorting by
noOfItems column in Descending Order.

package com.dilip.dao;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;

@Component
public class OrdersOperations {

@Autowired
AmazonOrderRepository repository;

public void getDataByPaginationAndSorting(int pageId, int noOFReorcds) {

List<AmazonOrders> allOrders =
repository.findAll(PageRequest.of(pageId, noOFReorcds,
Sort.by(Direction.DESC, "noOfItems"))).getContent();

System.out.println(allOrders);
}
}

➢ Execute Above Logic

package com.dilip;

209 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.dilip.dao.OrdersOperations;

@SpringBootApplication
public class SpringBootJpaTablesAutoCreationApplication {
public static void main(String[] args) {
ApplicationContext context
= SpringApplication.run(SpringBootJpaTablesAutoCreationApplication.class, args);
OrdersOperations ops = context.getBean(OrdersOperations.class);
ops.getDataByPaginationAndSorting(1,3);
}
}

Output: We got Entity Objects with Sorting by noOfItems column, and we got 2nd page set
of records.

[
AmazonOrders(orderId=3344, noOfItems=4, amount=3000.0, email=dilip@gmail.com,
pincode=500072, city=Hyderbad, gender=MALE),
AmazonOrders(orderId=3232, noOfItems=4, amount=63643.0, email=laxmi@gmail.com,
pincode=500070, city=Hyderbad, gender=FEMALE),
AmazonOrders(orderId=9988, noOfItems=3, amount=44444.0, email=ramesh@gmail.com,
pincode=600088, city=Chennai, gender=MALE)
]

Native Queries & JPQL Queries with Spring JPA:

Native Query is Custom SQL query. In order to define SQL Query to execute for a Spring
Data repository method, we have to annotate the method with the @Query annotation. This
annotation value attribute contains the SQL or JPQL to execute in Database. We will define
@Query above the method inside the repository.

Spring Data JPA allows you to execute native SQL queries by using the @Query annotation
with the nativeQuery attribute set to true. For example, the following method uses the
@Query annotation to execute a native SQL query that selects all customers from the
database.

@Query(value = "SELECT * FROM customer", nativeQuery = true)


public List<Customer> findAllCustomers();

The @Query annotation allows you to specify the SQL query that will be executed. The
nativeQuery attribute tells Spring Data JPA to execute the query as a native SQL query, rather
than considering it to JPQL.

JPQL Query:

210 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


The JPQL (Java Persistence Query Language) is an object-oriented query language
which is used to perform database operations on persistent entities. Instead of database
table, JPQL uses entity object model to operate the SQL queries. Here, the role of JPA is to
transform JPQL into SQL. Thus, it provides an easy platform for developers to handle SQL
tasks. JPQL is developed based on SQL syntax, but it won’t affect the database directly. JPQL
can retrieve information or data using SELECT clause, can do bulk updates using UPDATE
clause and DELETE clause.

By default, the query definition uses JPQL in Spring JPA. Let's look at a simple
repository method that returns Users entities based on city value from the database:

// JPQL Query in Repository Layer


@Query(value = "Select u from Users u")
List<Users> getUsers ();

JPQL can perform:


• It is a platform-independent query language.
• It can be used with any type of database such as MySQL, Oracle.
• join operations
• update and delete data in a bulk.
• It can perform aggregate function with sorting and grouping clauses.
• Single and multiple value result types.

Native SQL Query’s:

We can use @Query to define our Native Database SQL query. All we have to do is set
the value of the nativeQuery attribute to true and define the native SQL query in
the value attribute of the annotation.

Example, Below Repository Method representing Native SQL Query to get all records.

@Query(value = "select * from flipkart_users", nativeQuery = true)


List<Users> getUsers();

For passing values to Positional parameters of SQL Query from method parameters, JPA
provides 2 possible ways.

1. Indexed Query Parameters


2. Named Query Parameters

By using Indexed Query Parameters:

If SQL query contains positional parameters and we have to pass values to those, we should
use Indexed Params i.e. index count of parameters. For indexed parameters, Spring JPA Data

211 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


will pass method parameter values to the query in the same order they appear in the method
declaration.

Example: Get All Records Of Table

@Query(value = "select * from flipkart_users ", nativeQuery = true)


List<Users> getUsersByCity();

Example: Get All Records Of Table where city is matching

Now below method declaration in repository will return List of Entity Objects with city
parameter.

Example with more indexed parameters: users from either city or pincode matches.
Example: Get All Records Of Table where city or pincode is matching

Examples:

Requirement:
1. Get All Patient Details
2. Get All Patient with Email Id
3. Get All Patients with Age and Gender

Step 1: Define Methods Inside Repository with Native Queries:

package com.dilip.repository;

import java.util.List;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.dilip.entity.Patient;

212 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@Component
public interface PatientRepository extends CrudRepository<Patient, String> {

//Get All Patients


@Query(value = "select * from patient", nativeQuery = true)
public List<Patient> getAllPatients();

//Get All Patient with EmailId


@Query(value = "select * from patient where emailid=?1", nativeQuery = true)
public Patient getDetailsByEmail(String email);

//Get All Patients with Age and Gender


@Query(value = "select * from patient where age=?1 and gender=?2", nativeQuery = true)
public List<Patient> getPatientDetailsByAgeAndGender(int age, String gender);
}

➢ Step 2: Call Above Methods from DB Operations Class

package com.dilip.operations;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Component;
import com.dilip.entity.Patient;
import com.dilip.repository.PatientRepository;

@Component
public class PatientOperations {

@Autowired
PatientRepository repository;

//Select all patients


public List<Patient> getPatientDetails() {
return repository.getAllPatients();
}
//by email Id
public Patient getPatientDetailsbyEmailId(String email) {
return repository.getDetailsByEmail(email);
}
//age and gender
public List<Patient> getPatientDetailsbyAgeAndGender(int age, String gender) {
return repository.getPatientDetailsByAgeAndGender(age, gender);
}

213 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}

➢ Step 3: Testing From Main Method class

package com.dilip;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.dilip.dao.Patient;
import com.dilip.dao.PatientOperations;
import java.util.List;

@SpringBootApplication
public class PatientApplication {
public static void main(String[] args) {
ApplicationContext context =
SpringApplication.run(PatientApplication.class, args);

PatientOperations ops = context.getBean(PatientOperations.class);

//All Patients
List<Patient> allPatients = ops.getPatientDetails();
System.out.println(allPatients);

//By email Id
System.out.println("******** with email Id **************");
Patient patient = ops.getPatientDetailsbyEmailId("laxmi@gmail.com");
System.out.println(patient);

//By Age and Gender


System.out.println("******** PAteints with Age and gender**************");
List<Patient> patients = ops.getPatientDetailsbyAgeAndGender(31,"MALE");
System.out.println(patients);
}
}

Output:

214 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


By using Named Query Parameters:

We can also pass values of method parameters to the query using named parameters i.e. we
are providing We define these using the @Param annotation inside our repository method
declaration. Each parameter annotated with @Param must have a value string matching the
corresponding JPQL or SQL query parameter name. A query with named parameters is easier
to read and is less error-prone in case the query needs to be refactored.

NOTE: In JPQL also, we can use index and named Query parameters.
Requirement:
1. Insert Patient Data

Step 1: Define Method Inside Repository with Native Query:

package com.dilip.dao;

import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.dilip.entity.Patient;

215 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@Component
public interface PatientRepository extends CrudRepository<Patient, String> {

//adding Patient Details


@Transactional
@Modifying
@Query(value = "INSERT INTO patient VALUES(:emailId,:age,:contact,:gender,:name)",
nativeQuery = true)
public void addPAtient( @Param("name") String name,
@Param("emailId") String email,
@Param("age") int age,
@Param("contact") String mobile,
@Param("gender") String gender );
}

Step 2: Call Above Method from DB Operations Class

package com.dilip.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Component;
import com.dilip.entity.Patient;
import com.dilip.repository.PatientRepository;

@Component
public class PatientOperations {

@Autowired
PatientRepository repository;

//add Pateint
public void addPAtient(String name, String email, int age, String mobile, String gender) {
repository.addPAtient(name, email, age, mobile, gender);
}
}

Step 3: Test it From Main Method class.

package com.dilip;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.dilip.dao.Patient;

216 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


import com.dilip.dao.PatientOperations;

@SpringBootApplication
public class PatientApplication {
public static void main(String[] args) {
ApplicationContext context =
SpringApplication.run(PatientApplication.class, args);
PatientOperations ops = context.getBean(PatientOperations.class);
//add Pateint
System.out.println("*** Adding Patient ************");
ops.addPAtient("Rakhi", "Rakhi@gmail.com", 44, "+91372372", "MALE");
}
}

Output:

In above We executed DML Query, So it means some Modification will happen finally in
Database Tables data. In Spring JPA, for DML Queries like insert, update and delete provided
mandatory annotations @Transactional and @Modifying. We should declare these
annotations while executing DML Queries.

@Transactional:

Package : org.springframework.transaction.annotation.Transactional

In Spring Framework, the @Transactional annotation is used to indicate that a


method, or all methods within a class, should be executed within a transaction context.
Transactions are used to ensure data integrity and consistency in applications that involve
database operations. Specifically, when used with Spring Data JPA, the @Transactional
annotation plays a significant role in managing transactions around JPA (Java Persistence API)
operations.

Describes a transaction attribute on an individual method or on a class. When this


annotation is declared at the class level, it applies as a default to all methods of the declaring
class and its subclasses. If no custom rollback rules are configured in this annotation, the
transaction will roll back on RuntimeException and Error but not on checked exceptions.

@Modifying:

The @Modifying annotation in Spring JPA is used to indicate that a method is a modifying
query, which means that it will update, delete, or insert data in the database. This annotation
is used in conjunction with the @Query annotation to specify the query that the method will

217 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


execute. The @Modifying annotation is a powerful tool that can be used to update, delete,
and insert data in the database. It is often used in conjunction with the @Transactional
annotation to ensure that the data is updated or deleted in a safe and consistent manner.

Here are some of the benefits of using the @Modifying annotation:

• It makes it easy to update, delete, and insert data in the database.


• It can be used in conjunction with the @Transactional annotation to ensure that the data
is updated or deleted in a safe and consistent manner.
• It can be used to optimize performance by batching updates and deletes.

If you are developing an application that needs to update, delete, or insert data in the
database, I highly recommend using the @Modifying annotation. It is a powerful tool that
can help you to improve the performance and reliability of your application.

JPQL Queries Execution:

Examples for executing JPQL Query’s. Here We will not use nativeQuery attribute means by
default false value. Then Spring JPA considers @Query Value as JPQL Query.

Requirement:
• Fetch All Patients
• Fetch All Patients Names
• Fetch All Male Patients Names

Step1: Define Repository Methods along with JPQL Queries.

package com.dilip.repository;

import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;
import com.dilip.entity.Patient;

@Component
public interface PatientRepository extends CrudRepository<Patient, String> {

//JPQL Queries
//Fetch All Patients
@Query(value="Select p from Patient p")
public List<Patient> getAllPAtients();

//Fetch All Patients Names


@Query(value="Select p.name from Patient p")
public List<String> getAllPatientsNames();

218 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


//Fetch All Male Patients Names
@Query(value="Select p from Patient p where gender=?1")
public List<Patient> getPatientsByGender(String gender);
}

Step 2: Call Above Methods From DB Operations class.

package com.dilip.operations;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.dilip.entity.Patient;
import com.dilip.repository.PatientRepository;

@Component
public class PatientOperations {

@Autowired
PatientRepository repository;

// All Patients
public List<Patient> getAllpatients() {
return repository.getAllPAtients();
}
// All Patients Names
public List<String> getAllpatientsNames() {
return repository.getAllPatientsNames();
}
// All Patients Names
public List<Patient> getAllpatientsByGender(String gender) {
return repository.getPatientsByGender(gender);
}
}

Step 3: Test it From Main Method class.

package com.dilip;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.dilip.dao.Patient;
import com.dilip.dao.PatientOperations;

@SpringBootApplication

219 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


public class PatientApplication {
public static void main(String[] args) {
ApplicationContext context =
SpringApplication.run(PatientApplication.class, args);
PatientOperations ops = context.getBean(PatientOperations.class);
System.out.println("====> All Patients Details ");
System.out.println(ops.getAllpatients());
System.out.println("====> All Patients Names ");
System.out.println(ops.getAllpatientsNames());
System.out.println("====> All MALE Patients Details ");
System.out.println(ops.getAllpatientsByGender("MALE"));
}
}

Output:

Internally JPA Translates JPQL queries to Actual Database SQL Queries and finally those
queries will be executed. We can see those queries in Console Messages.

JPQL Query Guidelines

JPQL queries follow a set of rules that define how they are parsed and executed. These rules
are defined in the JPA specification. Here are some of the key rules of JPQL:

• The SELECT clause: The SELECT clause specifies the entities that will be returned by the
query.
• The FROM clause: The FROM clause specifies the entities that the query will be executed
against.
• The WHERE clause: The WHERE clause specifies the conditions that the entities must meet
in order to be included in the results of the query.

220 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


• The GROUP BY clause: The GROUP BY clause specifies the columns that the results of the
query will be grouped by.
• The HAVING clause: The HAVING clause specifies the conditions that the groups must
meet in order to be included in the results of the query.
• The ORDER BY clause: The ORDER BY clause specifies the order in which the results of the
query will be returned.
Here are some additional things to keep in mind when writing JPQL queries:

• JPQL queries are case-insensitive. This means that you can use the names of entities and
columns in either upper or lower case.
• JPQL queries can use parameters. Parameters are variables that can be used in the query
to represent values that are not known at the time the query is written.

Spring Framework JPA Project Configuration:


• For using Spring Data JPA, first of all we have to configure DataSource bean. Then we need
to configure LocalContainerEntityManagerFactoryBean bean.
• The next step is to configure bean for transaction management. In our example
it’s JpaTransactionManager.
• @EnableTransactionManagement: This annotation allows users to use transaction
management in application.
• @EnableJpaRepositories("com.flipkart.*"): indicates where the repositories classes are
present.

Configuring the DataSource Bean:

• Configure the database connection. We need to set the name of the the JDBC url, the
username of database user, and the password of the database user.
Configuring the Entity Manager Factory Bean:
We can configure the entity manager factory bean by following steps:
• Create a new LocalContainerEntityManagerFactoryBean object. We need to create this
object because it creates the JPA EntityManagerFactory.
• Configure the Created DataSource in Previous Step.
• Configure the Hibernate specific implementation of the HibernateJpaVendorAdapter . It will
initialize our configuration with the default settings that are compatible with Hibernate.
• Configure the packages that are scanned for entity classes.
• Configure the JPA/Hibernate properties that are used to provide additional configuration
to the used JPA provider.

Configuring the Transaction Manager Bean:

221 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Because we are using JPA, we have to create a transaction manager bean that
integrates the JPA provider with the Spring transaction mechanism. We can do this by using
the JpaTransactionManager class as the transaction manager of our application.

We can configure the transaction manager bean by following steps:


• Create a new JpaTransactionManager object.
• Configure the entity manager factory whose transactions are managed by the created
JpaTransactionManager object.

package flipkart.entity;

import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
@EnableJpaRepositories("flipkart.*")
public class SpringJpaConfiguration {

//DB Details
@Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:orcl");
dataSource.setUsername("c##dilip");
dataSource.setPassword("dilip");
return dataSource;
}

@Bean("entityManagerFactory")
LocalContainerEntityManagerFactoryBean createEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory
= new LocalContainerEntityManagerFactoryBean();

// 1. Setting Datasource Object // DB details


factory.setDataSource(getDataSource());
// 2. Provide package information of entity classes
factory.setPackagesToScan("flipkart.*");
// 3. Providing Hibernate Properties to EM
factory.setJpaProperties(hibernateProperties());

222 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


// 4. Passing Predefined Hiberante Adaptor Object EM
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
factory.setJpaVendorAdapter(adapter);

return factory;
}

@Bean("transactionManager")
public PlatformTransactionManager createTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(createEntityManagerFactory()
.getObject());
return transactionManager;
}

// these are all from hibernate FW , Predefined properties : Keys


Properties hibernateProperties() {

Properties hibernateProperties = new Properties();


hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "create");

//This is for printing internally genearted SQL Quries


hibernateProperties.setProperty("hibernate.show_sql", "true");
return hibernateProperties;
}
}

Now create another Component class For Performing DB operations as per our
Requirement:

package flipkart.entity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

// To Execute/Perform DB operations
@Component
public class OrderDbOperations {

@Autowired
FlipakartOrderRepository flipakartOrderRepository;

public void addOrderDetaisl(FlipakartOrder order) {


flipakartOrderRepository.save(order);
}
}

223 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Now Create a Main method class for creating Spring Application Context for loading all
Configurations and Component classes.

package flipkart.entity;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainApp {

public static void main(String[] args) {

AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
context.scan("flipkart.*");
context.refresh();

// Created Entity Object


FlipakartOrder order = new FlipakartOrder();
order.setOrderID(9988);
order.setProductName("Book");
order.setTotalAmount(333.00);

// Pass Entity Object to Repository MEthod


OrderDbOperations dbOperation = context.getBean(OrderDbOperations.class);
dbOperation.addOrderDetaisl(order);
}
}

Execute The Programme Now. Verify In Database Now.

In Eclipse Console Logs, Printed internally generated SQL Quries to perform insert operation.

NOTE: In our example, we are nowhere written any SQL query to do Database operation.

224 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Internally, Based on Repository method save() of flipakartOrderRepository.save(order), JPA
internally generates implementation code, SQL queries and will be executed internally.

Similarly, we have many predefined methods of Spring repository to do CRUD operations.

We learned to configure the persistence layer of a Spring application that uses Spring Data
JPA and Hibernate. Let’s create few more examples to do CRUD operations on Db table.

From Spring JPA Configuration class, we have used two properties related to Hibernate FW.

hibernate.hbm2ddl.auto: The `hibernate.hbm2ddl.auto` property is used to configure


the automatic schema/tables generation and management behaviour of Hibernate. This
property allows you to control how Hibernate handles the database schema based on your
entity classes.

Here are the possible values for the hibernate.hbm2ddl.auto property:

none: No action is performed. The schema will not be generated.


validate: The database schema will be validated using the entity mappings. This means that
Hibernate will check to see if the database schema matches the entity mappings. If there are
any differences, Hibernate will throw an exception.
update: The database schema will be updated by comparing the existing database schema
with the entity mappings. This means that Hibernate will create or modify tables in the
database as needed to match the entity mappings.
create: The database schema will be created. This means that Hibernate will create all of the
tables needed for the entity mappings.
create-drop: The database schema will be created and then dropped when the SessionFactory
is closed. This means that Hibernate will create all of the tables needed for the entity
mappings, and then drop them when the SessionFactory is closed.

Note: In Spring Boot, we are using property spring.jpa.hibernate.ddl-


auto with same values for same functionalities as we discussed.

hibernate.show_sql: The hibernate.show_sql property is a Hibernate configuration


property that controls whether or not Hibernate will log the SQL statements that it generates.
The possible values for this property are:

true: Hibernate will log all SQL statements to the console.


false: Hibernate will not log any SQL statements.

The default value for this property is false. This means that Hibernate will not log any SQL
statements by default. If you want to see the SQL statements that Hibernate is generating,
you will need to set this property to true.

225 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Logging SQL statements can be useful for debugging purposes. If you are having problems
with your application, you can enable logging and see what SQL statements Hibernate is
generating. This can help you to identify the source of the problem.

Note: In Spring Boot, we are using property spring.jpa.show-sql with same


values for same functionalities as we discussed.

Creation of New Spring JPA Project:

Requirement : Patient Information

• Name
• Age
• Gender
• Contact Number
• Email Id
Requirements:

➢ Add Single Patient Details


➢ Add More Than One Patient Details
➢ Update Patient Details
➢ Select Single Patient Details
➢ Select More Patient Details
➢ Delete Patient Details

1. Create Simple Maven Project and Add Required Dependencies

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

226 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dilip</groupId>
<artifactId>spring-jpa-two</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>6.0.11</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.11</version>
</dependency>
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>21.9.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>6.0.11</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.2.6.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>3.1.2</version>
</dependency>
</dependencies>
</project>

2. Now Create Spring JPA Configuration

package com.dilip;

import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;

227 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
@EnableJpaRepositories("com.*")
public class SpringJpaConfiguration {

//DB Details
@Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:orcl");
dataSource.setUsername("c##dilip");
dataSource.setPassword("dilip");
return dataSource;
}

@Bean("entityManagerFactory")
LocalContainerEntityManagerFactoryBean createEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();

// 1. Setting Datasource Object // DB details


factory.setDataSource(getDataSource());

// 2. Provide package information of entity classes


factory.setPackagesToScan("com.*");

// 3. Providing Hibernate Properties to EM


factory.setJpaProperties(hibernateProperties());

// 4. Passing Predefined Hiberante Adaptor Object EM


HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
factory.setJpaVendorAdapter(adapter);

return factory;
}

//Spring JPA: configuring data based on your project req.


@Bean("transactionManager")
public PlatformTransactionManager createTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(createEntityManagerFactory().getObject());
return transactionManager;
}

// these are all from hibernate FW , Predefined properties : Keys


Properties hibernateProperties() {
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "update");
//This is for printing internally genearted SQL Quries

228 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


hibernateProperties.setProperty("hibernate.show_sql", "true");
return hibernateProperties;
}

Note: Until this Step/Configuration in Spring Framework, we have written manually of JPA
configuration. From here onwards, Rest of functionalities implementations are as it is like how
we implemented in Spring Boot.

Means, The above 2 Steps are automated/ auto configured in Spring Boot internally. We just
need to provide database details and JPA properties inside application.properties.

3. Create Entity Class

NOTE : Configured hibernate.hbm2ddl.auto value as update. So Table Creation will be done


by JPA internally.

package com.dilip.entity;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table
public class Patient {

@Id
@Column
private String emailId;

@Column
private String name;

@Column
private int age;

@Column
private String gender;

@Column
private String contact;

public Patient() {
super();
// TODO Auto-generated constructor stub

229 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}

public Patient(String name, int age, String gender, String contact, String emailId) {
super();
this.name = name;
this.age = age;
this.gender = gender;
this.contact = contact;
this.emailId = emailId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}

@Override
public String toString() {
return "Patient [name=" + name + ", age=" + age + ", gender=" + gender + ",
contact=" + contact + ", emailId="
+ emailId + "]";
}
}

4. Create A Repository Now

230 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@Component
public interface PatientRepository extends CrudRepository<Patient, String> {

5. Create a class for DB operations

@Component
public class PatientOperations {
@Autowired
PatientRepository repository;
}

Spring JPA Repositories Provided many predefined abstract methods for all DB CURD
operations. We should recognize those as per our DB operation.

Requirement : Add Single Patient Details


Here, we are adding Patient details means at Database level this is insert Query Operation.

save() : Used for insertion of Details. We should pass Entity Object.

Add Below Method in PatientOperations.java:

public void addPatient(Patient p) {


repository.save(p);
}

Now Test it : Create Main method class

package com.dilip.operations;

import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.dilip.entity.Patient;

public class PatientApplication {

public static void main(String[] args) {

AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
context.scan("com.*");
context.refresh();

PatientOperations ops = context.getBean(PatientOperations.class);

231 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


// Add Single Patient
Patient p = new Patient();
p.setEmailId("one@gmail.com");
p.setName("One Singh");
p.setContact("+918826111377");
p.setAge(30);
p.setGender("MALE");

ops.addPatient(p);
}
}

Now Execute It. Table also created by JPA module and One Record is inserted.

Requirement : Add multiple Patient Details at a time

Here, we are adding Multiple Patient details means at Database level this is also insert Query
Operation.

saveAll() : This is for adding List of Objects at a time. We should pass List Object of Patient
Type.

Add Below Method in PatientOperations.java:

public void addMorePatients(List<Patient> patients) {


repository.saveAll(patients);
}

Now Test it : Inside Main method class, add Logic below.

package com.dilip.operations;

import java.util.ArrayList;
import java.util.List;

232 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.dilip.entity.Patient;

public class PatientApplication {

public static void main(String[] args) {

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();


context.scan("com.*");
context.refresh();

PatientOperations ops = context.getBean(PatientOperations.class);

// Adding More Patients


Patient p1 = new Patient();
p1.setEmailId("two@gmail.com");
p1.setName("Two Singh");
p1.setContact("+828388");
p1.setAge(30);
p1.setGender("MALE");

Patient p2 = new Patient();


p2.setEmailId("three@gmail.com");
p2.setName("Xyz Singh");
p2.setContact("+44343423");
p2.setAge(36);
p2.setGender("FEMALE");

List<Patient> allPatients = new ArrayList<>();


allPatients.add(p1);
allPatients.add(p2);
ops.addMorePatients(allPatients);
}
}

Execution Output:

233 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Verify In DB Table:

Requirement : Update Patient Details

In Spring Data JPA, the save() method is commonly used for both insert and update
operations. When you call the save() method on a repository, Spring Data JPA checks whether
the entity you're trying to save already exists in the database. If it does, it updates the existing
entity; otherwise, it inserts a new entity.

So that is the reason we are seeing a select query execution before inserting data in
previous example. After select query execution with primary key column JPA checks row
count and if it is 1, then JPA will convert entity as insert operation. If count is 0 , then Spring
JPA will convert entity as update operation specific to Primary key.

Using the save() method for updates is a common and convenient approach, especially when
we want to leverage Spring Data JPA's automatic change tracking and transaction
management.

Requirement: Please update name as Dilip Singh for email id: one@gmail.com

Add Below Method in PatientOperations.java:

public void updatePateinData(Patient p) {

234 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


repository.save(p);
}

Now Test it from Main class: In below if we observe, first select query executed by JPA as
per our entity Object, JPA found data so JPA decided for update Query execution.

Verify In DB :

Requirement: Deleting Patient Details based on Email ID.

Spring JPA provided a predefined method deleteById() for primary key columns delete
operations.

deleteById():

235 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


The deleteById() method in Spring Data JPA is used to remove an entity from the
database based on its primary key (ID). It's provided by the JpaRepository interface and allows
you to delete a single entity by its unique identifier.

Here's how you can use the deleteById() method in a Spring Data JPA repository:

Add Below Method in PatientOperations.java:

public void deletePatient(String email) {


repository.deleteById(email);
}

Testing from Main Class:

package com.dilip.operations;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class PatientApplication {


public static void main(String[] args) {

AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
context.scan("com.*");
context.refresh();

PatientOperations ops = context.getBean(PatientOperations.class);


//Delete Patient Details
ops.deletePateintWithEmailID("two@gmail.com");
}
}

Before Execution/Deletion:

After Execution/Deletion:

236 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Requirement: Get Patient Details Based on Email Id.

Here Email Id is Primary key Column. Finding Details based on Primary key column
name Spring JPA provide a method findById().

Add Below Method in PatientOperations.java:

public Patient fetchByEmailId(String emailId) {


return repository.findById(emailId).get();
}

Testing from Main Class:

package com.dilip.operations;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.dilip.entity.Patient;

public class PatientApplication {

public static void main(String[] args) {


AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext();
context.scan("com.*");
context.refresh();

PatientOperations ops = context.getBean(PatientOperations.class);


//Fetch Patient Details By Email ID
Patient patient = ops.fetchByEmailId("dilip@gmail.com");
System.out.println(patient);
}
}

Output:

237 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Remaining all functionalities are similar like we discussed in Spring BOOT.

Spring/SpringBoot
Web/MVC
Modules

238 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Spring Web MVC is the original web framework built on the Servlet API and has been
included in the Spring Framework from the very beginning. The formal name, "Spring Web
MVC," comes from the name of its source module (spring-webmvc), but it is more commonly
known as "Spring MVC". A Spring MVC is a Java framework which is used to build web
applications. It follows the Model-View-Controller design pattern. It implements all the basic
features of a core spring framework like Inversion of Control, Dependency Injection.

A Spring MVC provides an elegant solution to use MVC in spring framework by the
help of DispatcherServlet. Here, DispatcherServlet is a class that receives the incoming
request and maps it to the right resource such as controllers, models, and views.

Spring Boot is well suited for web application development. You can create a self-contained
HTTP server by using embedded Tomcat, Jetty, Undertow, or Netty. Most web applications
use the SpringBoot-starter-web module to get up and running quickly.

What is MVC?
MVC stands for Model-View-Controller, and it is a widely used architectural pattern in
software development, particularly for building user interfaces and web applications. MVC is
designed to separate an application into three interconnected components, each with a
specific responsibility:

MVC Architecture becomes so popular that now most of the popular frameworks
follow the MVC design pattern to develop the applications. Some of the popular Frameworks
that follow the MVC Design pattern are:

• JAVA Frameworks: Sprint, Spring Boot.


• Python Framework: Django.
• NodeJS (JavaScript): ExpressJS.
• PHP Framework: Cake PHP, Phalcon, PHPixie.
• Ruby: Ruby on Rails.
• Microsoft.NET: ASP.net MVC.

239 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Model:
The Model component corresponds to all the data-related logic that the user works
with. This can represent either the data that is being transferred between the View and
Controller components or any other business logic-related data. For example, a Customer
object will retrieve the customer information from the database, manipulate it and update it
data back to the database or use it to render data.

View:
The View component is used for all the UI logic of the application. For example, the
Customer view will include all the UI components such as text boxes, dropdowns, etc. that
the final user interacts with.
Controller:

Controllers act as an interface between Model and View components to process all
the business logic and incoming requests, manipulate data using the Model component and
interact with the Views to render the final output. For example, the Customer controller will
handle all the interactions and inputs from the Customer View and update the database using
the Customer Model. The same controller will be used to view the Customer data.

Here's how the MVC pattern works in a typical scenario:

1. A user interacts with the View (e.g., clicks a button or submits a form).
2. The View forwards the user input to the Controller.
3. The Controller processes the input, potentially querying or updating the Model.
4. The Model is updated if necessary, and the Controller retrieves data from the Model.
5. The Controller sends the updated data to the View.
6. The View renders the data and presents it to the user.

240 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Advantages of Spring MVC Framework

• Separate roles - The Spring MVC separates each role, where the model object, controller,
view resolver, DispatcherServlet, validator, etc. can be fulfilled by a specialized object.
• Light-weight - It uses light-weight servlet container to develop and deploy your
application.
• Powerful Configuration - It provides a robust configuration for both framework and
application classes that includes easy referencing across contexts, such as from web
controllers to business objects and validators.
• Rapid development - The Spring MVC facilitates fast and parallel development.
• Reusable business code - Instead of creating new objects, it allows us to use the existing
business objects.
• Easy to test - In Spring, generally we create JavaBeans classes that enable you to inject
test data using the setter methods.
• Flexible Mapping - It provides the specific annotations that easily redirect the page.

MVC is a foundational pattern used in various software development paradigms, including


desktop applications, web applications, and mobile applications. Different platforms and
frameworks may implement MVC in slightly different ways, such as Model-View-Presenter
(MVP) or Model-View-View-Model (MVVM), but the core principles of separation of concerns
and data flow remain consistent.

Creating SpringBoot Web Application:

Open STS : File-> New > Spring Starter Project

241 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Fill All Project details as shown below and click on Next.

In Next Page, Add Spring Boot Modules/Starters as shown below and click on finish.

242 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


After finish the project look like this all your dependencies in pom.xml file

Now Run your Application as Spring Boot App / java application from Main Method
Class.

➢ Integrated Server Started with Default Port : 8080 with context path ' '. i.e., if we won’t
give any port number then default port number will be 8080. If we want to change default
port number then, we should add a property and its value in application.properties.
➢ By Default Spring Boot application will be deployed with empty context path ' '. If we
want to change default context path then, we should add a property and its value in
application.properties.

So our application base URL will be always : http://localhost:8080/

243 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Requirement: Now Let me add an Endpoint/URL to print Hello World Message.

Controller Class:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloWorldController {
@GetMapping("/world")
@ResponseBody
public String printHelloWrold() {
return "Hello world! Welcome to Spring Boot MVC";
}
}

Execute/Call above Endpoint: We will access Endpoints/URLs from Http Clients like Browsers.

Changing Default Port Number and Context path of Application:

Now open application. Properties file and add below predefined properties and provide
required values.

server.port=8899
server.servlet.context-path= /hello

➢ Restart our application again, application started on port(s): 8899 (http) with context
path '/hello'

So our application base URL will become now always : http://localhost:8899/hello

244 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Output: Call “/world” endpoint : http://localhost:8899/hello/world

Spring MVC Application Internal Workflow:

Usually, Spring MVC Application follows below architecture on high level.

245 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Internal Workflow of Spring MVC Application i.e., Request & Response Handling:

The Spring Web Model-View-Controller (MVC) framework is designed around a Front


Controller Design Pattern i.e. DispatcherServlet that handles all the HTTP requests and
responses across Spring Web application. The request and response processing workflow of
the Spring Web MVC DispatcherServlet is illustrated in the following diagram.

Front Controller:
A front controller is defined as a controller that handles all requests for a Web
Application. DispatcherServlet servlet is the front controller in Spring MVC that intercepts
every request and then dispatches requests to an appropriate controller. The
DispatcherServlet is a Front Controller and one of the most significant components of the
Spring MVC web framework. A Front Controller is a typical structure in web applications that
receives requests and delegates their processing to other components in the application. The
DispatcherServlet acts as a single entry point for client requests to the Spring MVC web
application, forwarding them to the appropriate Spring MVC controllers for processing.
DispatcherServlet is a front controller that also helps with view resolution, error handling,
locale resolution, theme resolution, and other things.

Request: The first step in the MVC flow is when a request is received by the Dispatcher Servlet.
The aim of the request is to access a resource on the server.
Response: Response is made by a server to a client. The aim of the response is to provide the
client with the resource it requested, or inform the client that the action it requested has been
carried out; or else to inform the client that an error occurred in processing its request.
Dispatcher Servlet: Now, the DispatcherServlet with the help of Handler Mappings
understands the Controller class name associated with the received request. Once the
DispatcherServlet knows which Controller will be able to handle the request, it will transfer
the request to it. DispatcherServlet expects a WebApplicationContext (an extension of a
plain ApplicationContext) for its own configuration. WebApplicationContext has a link to the
ServletContext and the Servlet with which it is associated.

246 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


The DispatcherServlet delegates to special beans to process requests and render the
appropriate responses.

All the above-mentioned components, i.e. HandlerMapping, Controller, and ViewResolver


are parts of WebApplicationContext which is an extension of the plain ApplicationContext
with some extra features necessary for web applications.

HandlerMapping:

In Spring MVC, the DispatcherServlet acts as front controller – receiving all incoming HTTP
requests and processing them. Simply put, the processing occurs by passing the requests to
the relevant component with the help of handler mappings.

HandlerMapping is an interface that defines a mapping between requests and handler


objects. The HandlerMapping component parses a Request and finds a Handler that handles
the Request, which is generally understood as a method in the Controller.

Now Define Controller classes inside our Spring Boot MVC application:

Create a controller class : IphoneCotroller.java

package com.apple.iphone.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class IphoneCotroller {

@GetMapping("/message")
@ResponseBody
public String printIphoneMessage() {
//Logic of Method
return " Welcome to Iphone World.";
}
@GetMapping("/cost")
@ResponseBody
public String printIphone14Cost() {
return " Price is INR : 150000";
}
}

247 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Create another Controller class : IpadControlller.java

package com.apple.iphone.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class IpadControlller {
@GetMapping("/ipad/cost")
@ResponseBody
public String printIPadCost() {
return " Ipad Price is INR : 200000";
}
}

Project Folder and File Structure:

Now when we start our project as Spring Boot Application, Internally Project deployed to
tomcat server and below steps will be executed.
• When we are started/deployed out application, Spring MVC internally creates
WebApplcationContext i.e. Spring Container to instantiate and manage all Spring Beans
associated to our project.
• Spring instantiates Pre-Defined Front Controller class called as DispatcherServlet as well
as WebApplicationContext scans all our packages for @Component, @Controller etc..
and other Bean Configurations.

248 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


• Spring MVC WebApplicationContext will scan all our Controller classes which are marked
with @Controller and starts creating Handler Mappings of all URL patterns defined in side
controller classes with Controller and endpoint method names mappings.

In our App level, we created 2 controller classes with total 3 endpoints/URL-patterns.

After Starting our Spring Boot Application, when we are sending a request, Following
is the sequence of events happens corresponding to an incoming HTTP request
to DispatcherServlet:
For example, we sent a request to our endpoint from browser:
http://localhost:6655/apple/message
➢ After receiving an HTTP request, DispatcherServlet consults the HandlerMappings by
passing URI (/message) and HTTP Method type GET.
➢ Then HandlerMappings will checks all mappings information with above Details, If details
are mapped then HandlerMapping will returns Controller Class Name and Method Name.
➢ If Details are not mapped/found in mappings, then HandlerMappings will provide an error
message to DispatcherServlet with Error Details.
➢ After DispatcherServlet Receiving appropriate Controller and its associated method of
endpoint URI, then DispatcherServlet forwards all request body and parameters to
controller method and executes same.
➢ The Controller takes the request from DispatcherServlet and calls the appropriate service
methods.
➢ The service method will set model data based on defined business logic and returns result
or response data to Controller and from Controller to DispatcherServlet.
➢ If We configured ViewResolver, The DispatcherServlet will take help
from ViewResolver to pick up the defined view i.e. JSP files to render response of for that
specific request.

249 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ Once view is finalized, The DispatcherServlet passes the model data to the view which is
finally rendered on the browser.
➢ If no ViewResolver configured then Server will render the response on Browser or ANY
Http Client as default test/JSON format response.

NOTE: As per REST API/Services, we are not integrating Frontend/View layer with our
controller layer i.e. We are implementing individual backend services and shared with
Frontend Development team to integrate with Our services. Same Services we can also share
with multiple third party applications to interact with our services to accomplish the task. So
We are continuing our training with REST services implantation point of view because in
Microservices Architecture communication between multiple services happens via REST APIS
integration across multiple Services.

Controller Class:

In Spring Boot, the controller class is responsible for processing incoming HTTP web
requests, preparing a model, and returning the view to be rendered as a response on client.
The controller classes in Spring are annotated either by the @Controller or the
@RestController annotation.

@Controller: org.springframework.stereotype.Controller

The @Controller annotation is a specialization of the generic stereotype


@Component annotation, which allows a class to be recognized as a Spring-managed
component. @Controller annotation indicates that the annotated class is a controller. It is a
specialization of @Component and is autodetected through class path/component scanning.
It is typically used in combination with annotated handler methods based on the
@RequestMapping annotation.

@ResponseBody:

Package: org.springframework.web.bind.annotation.ResponseBody:

We annotated the request handling method with @ResponseBody. This annotation


enables automatic serialization of the return object into the HttpResponse. This indicates a
method return value should be bound to the web response i.e. HttpResponse body.
Supported for annotated handler methods. The @ResponseBody annotation tells a controller
that the object returned is automatically serialized into JSON and passed back into the
HttpResponse object.

@RequestMapping:

Package: org.springframework.web.bind.annotation.RequestMapping

This Annotation for mapping web requests onto methods in request-handling classes i.e.
controller classes with flexible method signatures. @RequestMapping is Spring MVC's most
common and widely used annotation.

250 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


This Annotation has the following optional attributes.

Attribute Data Type Description


Name
name String Assign a name to this mapping.

value String[] The primary mapping expressed by this annotation.


method RequestMethod[] The HTTP request methods to map to, narrowing the
primary mapping: GET, POST, HEAD, OPTIONS, PUT, PATCH,
DELETE, TRACE.

headers String[] The headers of the mapped request, narrowing the


primary mapping.
path String[] The path mapping URIs (e.g. "/profile").
consumes String[] media types that can be consumed by the mapped handler.
Consists of one or more media types one of which must match
to the request Content-Type header.

consumes = "text/plain"
consumes = {"text/plain", "application/*"}
consumes = MediaType.TEXT_PLAIN_VALUE
produces String[] mapping by media types that can be produced by the mapped
handler. Consists of one or more media types one of which
must be chosen via content negotiation against the
"acceptable" media types of the request.

produces = "text/plain"
produces = {"text/plain", "application/*"}
produces = MediaType.TEXT_PLAIN_VALUE
produces = "text/plain;charset=UTF-8"

params String[] The parameters of the mapped request, narrowing the


primary mapping.

Same format for any environment: a sequence of


"myParam=myValue" style expressions, with a request
only mapped if each such parameter is found to have the
given value.

Note: This annotation can be used both at the class and at the method level. In most cases, at
the method level, applications will prefer to use one of the HTTP method specific variants
@GetMapping, @PostMapping, @PutMapping, @DeleteMapping.

251 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Example: @RequestMapping without any attributes with method level

package com.apple.iphone.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class IphoneCotroller {
@RequestMapping("/message")
@ResponseBody
public String printIphoneMessage() {
return " Welcome to Ihpne World.";
}
}

@RequestMapping("/message"):

1. If we are not defined in method type attribute and value, then same handler method will
be executed for all HTTP methods along with endpoint.
2. @RequestMapping("/message") is equivalent to @RequestMapping(value="/message")
or @RequestMapping(path="/message")

i.e. value and path are same type attributes to configure URI path of handler method. We
can use either of them i.e. value is an alias for path.

Example : With method attribute and one value:

@RequestMapping(value="/message", method = RequestMethod.GET)


@ResponseBody
public String printIphoneMessage() {
return " Welcome to Iphone World.";
}

Now above handler method will work only for HTTP GET request call. If we try to request with
any HTTP methods other than GET, we will get error response as

"status": 405,
"error": "Method Not Allowed",

252 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Example : method attribute having multiple values i.e. Single Handler method

@RequestMapping(value="/message",
method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public String printIphoneMessage() {
return " Welcome to Iphone World.";
}

Now above handler method will work only for HTTP GET and POST requests calls. If we try to
request with any HTTP methods other than GET, POST we will get error response as:

"status": 405,
"error": "Method Not Allowed",

i.e. we can configure one URL handler method with multiple HTTP
methods request.

Example : With Multiple URI values and method values:

@RequestMapping(value = { "/message", "/msg/iphone" },


method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public String printIphoneMessage() {
return " Welcome to Iphone World.";
}

Above handler method will support both GET and POST requests of URI’s mappings
"/message", "/msg/iphone".

RequestMethod:
RequestMethod is Enumeration(Enum) of HTTP request methods. Intended for use
with the RequestMapping.method() attribute of the RequestMapping annotation.

ENUM Constant Values : GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, TRACE

253 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Example : multiple Handler methods with same URI and different HTTP methods.

We can Define Same URI with multiple different handler/controller methods for different
HTTP methods. Depends on incoming HTTP method request type specific handler method will
be executed.

@RequestMapping(value = "/mac", method = RequestMethod.GET)


@ResponseBody
public String printMacMessage() {
return " Welcome to MAC World.";
}

@RequestMapping(value = "/mac", method = RequestMethod.POST)


@ResponseBody
public String printMac2Message() {
return " Welcome to MAC 2 World.";
}

Declaring @RequestMapping at Class Level:

We can use @RequestMapping with class definition level to create the base URI of
that specific controller i.e. All URI mappings of that controller will be preceded with class level
URI value always.

For example:

package com.apple.iphone.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/ipad")
public class IpadControlller {

@GetMapping("/cost")
@ResponseBody
public String printIPadCost() {
return " Ipad Price is INR : 200000";
}

@GetMapping("/model")
@ResponseBody
public String printIPadModel() {

254 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


return " Ipad Model is 2023 Mode";
}
}

From above example, class level Request mapping value ("/ipad") will be base URI for all
handler method URI values. Means All URIs starts with /ipad of the controller URI’s as shown
below.

http://localhost:6655/apple/ipad/model
http://localhost:6655/apple/ipad/cost

@GetMapping:

Package: org.springframework.web.bind.annotation.GetMapping

This Annotation used for mapping HTTP GET requests onto specific handler methods.
The @GetMapping annotation is a composed version of @RequestMapping annotation that
acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

The @GetMapping annotated methods handle the HTTP GET requests matched with the
given URI value.

Similar to this annotation, we have other Composed Annotations to handle different HTTP
methods.

@PostMapping:
This Annotation used for mapping HTTP POST requests onto specific handler methods.
@PostMapping is a composed annotation that acts as a shortcut for
@RequestMapping(method = RequestMethod.POST).

@PutMapping:
This Annotation used for mapping HTTP PUT requests onto specific handler methods.
@PutMapping is a composed annotation that acts as a shortcut for
@RequestMapping(method = RequestMethod.PUT).

@DeleteMapping:
This Annotation used for mapping HTTP DELETE requests onto specific handler
methods. @DeleteMapping is a composed annotation that acts as a shortcut for
@RequestMapping(method = RequestMethod.DELETE).

255 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


View Layer / JSP files Integration in Spring Boot MVC:

➢ Create A Spring Boot Web Application

➢ By default embedded tomcat server will not support JSP functionalities inside a Spring
Boot MVC application. So, In order to work with JSP, we need to add below dependency in
Spring boot MVC.

<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>

JSP ViewResolver Configuration in application.properties file:

What is ViewResolver?
In Spring MVC, a ViewResolver is an essential component responsible for resolving
logical view names returned by controller methods into actual view implementations that can
be rendered and returned to the client. It plays a crucial role in the web application's flow by
mapping logical view names to views, which can be JSP pages, HTML templates, or any other
type of view technology supported by Spring.

InternalResourceViewResolver:

InternalResourceViewResolver is a class in the Spring Framework used for view


resolution in a Spring web application. It's typically used when you are working with Java
Server Pages (JSP) as your view technology. InternalResourceViewResolver helps map logical
view names returned by controllers to physical JSP files within your application.

Here's how InternalResourceViewResolver works:

1. Controller Returns a Logical View Name: In a Spring web application, when a controller
method processes an HTTP request and returns a logical view name (e.g., "home" or
"dashboard"), this logical view name is returned to the Spring MVC framework.

2. InternalResourceViewResolver Resolves the View: The InternalResourceViewResolver is


configured in the Spring application context, and it is responsible for resolving logical view
names. It combines a prefix and suffix with the logical view name to construct the actual path
to the JSP file. For example, if the prefix is "/WEB-INF/view/" and the suffix is ".jsp," and the
logical view name is "home," then the resolver constructs the view path as "/WEB-
INF/view/home.jsp"

3. JSP Is Rendered: Once the view path is resolved, the JSP file at that path is executed. Any
dynamic data is processed, and the JSP generates HTML content that is sent as a response to
the client's browser.

256 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ Add below View resolver properties in application.properties file to configure view names
i.e. JSP files.

spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp

➢ Based on above configuration of property prefix value, we have to create folders inside
our Spring Boot MVC application.
➢ Create a folder webapp inside src -> main
➢ Inside webapp, create another folder WEB-INF
➢ Inside WEB-INF, create another folder view
➢ Inside view Folder, We will create our JSP files.

➢ Now create a JSP file inside view folder and invoke it from Controller Method.

Create JSP file : hello.jsp

<html>
<head>
<title>Spring Boot MVC</title>
</head>
<body>
<h1>Welcome to Spring Boot MVC with JSP</h1>
</body>
</html>

257 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ Now create a controller method and invoke above jsp file.

package com.facebook.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class UserController {
@GetMapping("/welcome")
public String sayHello() {
return "hello";
}
}

Testing: Send a Request to above URI method:

Internally, DispatcherServlet will forwards the request to jsp file as per our Internal
Resource View Resolver configuration data, i.e. inside folder /WEB-INF/view/ with suffix
.jsp by including jsp file name “hello”.

prefix + view name + suffix = /WEB-INF/view/hello.jsp

Above JSP loaded as Response now in client/browser side.

Service Layer in Spring MVC:

A service layer is a layer in an application that facilitates communication between the


controller and the persistence/repository layer. Additionally, business logic should be written
inside service layer. It defines which functionalities you provide, how they are accessed, and
what to pass and get in return. Even for simple CRUD cases, introduce a service layer, which
at least translates from DTOs to Entities and vice versa. A Service Layer defines an
application's boundary and its set of available operations from the perspective of interfacing

258 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


client layers. It encapsulates the application's business logic, controlling transactions and
coordinating responses in the implementation of its operations.

Spring MVC application Architecture

We are going annotate with @Service is annotated on class to say spring, this is my Service
Layer.
Create An Example with Service Layer:
Controller Class:

@Controller
@RequestMapping("/admission")
public class UniversityAdmissionsController {

//Logic

Service Class:

@Service
public class UniversityAdmissionsService {

//Logic

Now integrate Service Layer class with Controller Layer i.e. injecting Service class Object into
Controller class Object. So we will use @Autowired annotation to inject service in side
controller.

259 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@Controller
public class UniversityAdmissionsController {

//Injecting Service Class Object : Dependency Injection


@Autowired
UniversityAdmissionsService service;

//Logic
}

From above, We are integrated controller with service layer. Now inside Service class, we will
write Business Logic and then data should be passed to persistence layer.
Now return values of service class methods are passed to Controller class level. This is how
we are using service layer with controller layer. Now we should integrate Service layer with
DAO Layer to Perform DB operations. We will have multiple examples together of all three
layer.

Repository Layer:

Repository Layer is mainly used for managing the data with database in a Spring
Application. A huge amount of code is required for working with the databases, which can be
easily reduced by Spring Data modules. It consists of JPA and JDBC modules. There are many
Spring applications that use JPA technology, so these development procedures can be easily
simplified by Spring Data JPA. As we discussed earlier in JPA functionalities, Now we have to
integrate JPA Module to our existing application.
Repository Interface:

@Respository
public interface AdmissionsRepository extends JpaRepository {
//JPA Methods
}

Repository Integration with Service Class:

@Service
public class UniversityAdmissionsService {

@Autowired
AdmissionsRepository repository;

//Logic

260 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Spring Boot Web/MVC + JSP+ JPA Example:

Requirement: Create a Project and implement User Registration and Login Flows.

Create a Spring Project with Web and JPA Modules.

Add Database details and server port details inside application.properties.

server.port=9999
server.servlet.context-path=/tekteacher

#DB Properties.
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.username=c##dilip
spring.datasource.password=dilip

spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none

Now Add Dependency of JSP inside pom.xml file.

<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>

261 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Now Add ViewResolver properties of JSP inside application.properties file.

server.port=9999
server.servlet.context-path=/tekteacher

#DB Properties.
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.username=c##dilip
spring.datasource.password=dilip

spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

#JSP
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp

Create view folder as per prefix value inside our application.

262 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Create a JSP file for User Registration Form User Interface : user-register.jsp

<html>
<head>
<title> User Register</title>
</head>
<body>
<form action="user/register" method="POST">
Name : <input type="text" name="name" /> <br />
Email Id : <input type="text" name="email" /> <br />
Contact Number : <input type="text" name="contact" /> <br />
Password : <input type="password" name="pwd" /> <br />
<input type="submit" value="Register" /> <br />
</form>
</body>
</html>

Create another JSP file for User Registration Result Message, whether User Account
Created or Not : result.jsp

<html>
<head>
<title> Result</title>
</head>
<body>
${message}
</body>
</html>

Create a DTO class for retrieving details from HttpServeletRequest Object in side
Controller method.

package com.tek.teacher.dto;

public class UserReigtserDto {

private String name;


private String emailId;
private String contact;
private String password;

public String getName() {


return name;
}
public void setName(String name) {
this.name = name;

263 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

Create Controller class and Methods for loading User Registration Page and reading data
from Registration page. Once Receiving Data at controller we should store it inside
database.

Controller Class : UserController.java

package com.tek.teacher.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
import com.tek.teacher.dto.UserReigtserDto;
import com.tek.teacher.service.UserService;
import jakarta.servlet.http.HttpServletRequest;

@Controller
public class UserController {

@Autowired
UserService userService;

264 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


//for loading HTML UI Form
@GetMapping("register")
public String sayHello() {
return "register";
}

// From Action Endpoint for User Registration


@PostMapping("user/register")
public ModelAndView registerUser(HttpServletRequest request) {

//Extracting Data From HttpServletRequest to DTO


UserReigtserDto userReigtserDto = new UserReigtserDto();
userReigtserDto.setName(request.getParameter("name"));
userReigtserDto.setEmailId(request.getParameter("email"));
userReigtserDto.setContact(request.getParameter("contact"));
userReigtserDto.setPassword(request.getParameter("pwd"));

String result = userService.userRegistration(userReigtserDto);

ModelAndView modelAndView = new ModelAndView();


//setting result jsp file name
modelAndView.setViewName("result");
modelAndView.addObject("message", result);

return modelAndView;
}
}

Now Create Service Layer class and respective method for storing User Information inside
database.

package com.tek.teacher.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tek.teacher.dto.UserReigtserDto;
import com.tek.teacher.entity.UsersInfo;
import com.tek.teacher.repository.UserRepository;

@Service
public class UserService {

@Autowired
UserRepository repository;

public String userRegistration(UserReigtserDto userReigtserDto) {

265 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


// convert dto instance to entity object
UsersInfo user = new UsersInfo();
user.setContact(userReigtserDto.getContact());
user.setEmailId(userReigtserDto.getEmailId());
user.setName(userReigtserDto.getName());
user.setPassword(userReigtserDto.getPassword());
repository.save(user);

return "User Registration Successful.";


}
}

Now create JPA Entity class for Database Operations, with columns related to User Details.

package com.tek.teacher.entity;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table
public class UsersInfo{

@Id
@Column
private String emailId;

@Column
private String name;

@Column
private String contact;

@Column
private String password;

public String getEmailId() {


return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getName() {
return name;

266 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}
public void setName(String name) {
this.name = name;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

Now create a JPA Repository.

package com.tek.teacher.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.tek.teacher.entity.UsersInfo;

@Repository
public interface UserRepository extends JpaRepository<UsersInfo, String>{

Testing/Execution: Start Our Spring Boot Application

Now Access register URI : http://localhost:9999/tekteacher/register


This URL will load Form for entering User Details as followed.

267 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Now Enter User Information and then click on Register button. Internally it will trigger
another endpoint “user/register”

Response :

Finally User Information Successfully Stored Inside Database.

268 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Requirement: Login of User

Create Login UI Form : login.jsp

<html>
<head>
<title>Login User</title>
</head>
<body>
<form action="loginCheck" method="POST">
Email : <input type="text" name="email" /> <br />
Password : <input type="password" name="pwd" /> <br />
<input type="submit" value="Login" /> <br />
</form>
</body>
</html>

Now Create Controller Method For Login Page/Form Loading.

@GetMapping("login")
public ModelAndView loadLoginPage() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("login");
return modelAndView;
}

Now Create Controller Method For Receiving Login Form Data and validation of User
Details.

@PostMapping("/loginCheck")
public ModelAndView validateUser(HttpServletRequest request) {

String result = userService.validateUser(request.getParameter("email"),


request.getParameter("pwd"));

ModelAndView modelAndView = new ModelAndView();


modelAndView.setViewName("result");
modelAndView.addObject("message", result);
return modelAndView;
}

269 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Create Another Method in Service Class to connect with Repository layer

public String validateUser(String emailId, String password) {


// Verify in data base
List<FacebookUsers> users = repository.findByEmailIdAndPassword(emailId,
password);
if (users.size() == 0) {
return "Invalid Credentials. Please Try again";
} else {
return "Welcome to FaceBook, " + emailId;
}
}

Create a custom findBy.. JPA method inside Repository Interface.

package com.facebook.repository;

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.facebook.entity.FacebookUsers;

@Repository
public interface UserRepository extends JpaRepository<FacebookUsers, String>{

List<FacebookUsers> findByEmailIdAndPassword(String emailId, String password);

Testing: Load Login From.

Now enter User Login Information.

270 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Valid User Credentials: Entered Valid Email Id and Password

Response :

Invalid User Credentials: Entered Invalid Email Id and Password

Response :

271 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


How to Choose HTTP methods?

Generally we will choose HTTP method depends on Data Base Operations of the
requirement i.e. When we are implementing Handler methods finally as part of implantation
which database query is executed as explained as follows.

CRUD Operations vs HTTP methods:

Create, Read, Update, and Delete — or CRUD — are the four major functions used to
interact with database applications. The acronym is popular among programmers, as it
provides a quick reminder of what data manipulation functions are needed for an application
to feel complete. Many programming languages and protocols have their own equivalent
of CRUD, often with slight variations in how the functions are named and what they do. For
example, SQL — a popular language for interacting with databases — calls the four functions
Insert, Select, Update, and Delete. CRUD also maps to the major HTTP methods.

Although there are numerous definitions for each of the CRUD functions, the basic idea is that
they accomplish the following in a collection of data:

NAME DESCRIPTION SQL EQUIVALENT

Create Adds one or more new entries Insert

Read Retrieves entries that match certain criteria (if there are any) Select

Update Changes specific fields in existing entries Update

Delete Entirely removes one or more existing entries Delete

Generally most of the time we will choose HTTP methods of an endpoint based on
Requirement Functionality performing which operation out of CRUD operations. This is a best
practice of creating REST API’s.

CRUD HTTP

CREATE POST

READ GET

UPDATE PUT

DELETE DELETE

272 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Webservices:
Web services are a standardized way for different software applications to
communicate and exchange data. They enable interoperability between various systems,
regardless of the programming languages or platforms they are built on. Web services use a
set of protocols and technologies to enable communication and data exchange between
different applications, making it possible for them to work together without any issues.

Web services are used to integrate different applications and systems, regardless of their
platform or programming language. They can be used to provide a variety of services, such
as:
• Information retrieval
• Transaction processing
• Data exchange
• Business process automation

There are two main types of web services:

1. SOAP (Simple Object Access Protocol) Web Services:

SOAP is a protocol for exchanging structured information using XML. It provides a way
for applications to communicate by sending messages in a predefined format. SOAP web
services offer a well-defined contract for communication and are often used in enterprise-
level applications due to their security features and support for more complex scenarios.

2. REST (Representational State Transfer) Web Services:

REST is an architectural style that uses HTTP methods (GET, POST, PUT, DELETE) to
interact with resources in a stateless manner. RESTful services are simple, lightweight, and
widely used due to their compatibility with the HTTP protocol. They are commonly used for
building APIs that can be consumed by various clients, such as web and mobile applications.
The choice of web service type depends on factors such as the nature of the application, the
level of security required, the complexity of communication, and the preferred data format.

REST API:

RESTful API is an interface that two computer systems use to exchange information
securely over the internet. Most business applications have to communicate with other
internal and third-party applications to perform various tasks.

API: An API is a set of definitions and protocols for building and integrating application
software. It’s sometimes referred to as a contract between an information provider and an
information consumer. An application programming interface (API) defines the rules that you
must follow to communicate with other software systems. Developers expose or create APIs
so that other applications can communicate with their applications programmatically. For
example, the ICICI application exposes an API that asks for banking users, Card Details , Name,

273 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


CVV etc.. When it receives this information, it internally processes the users data and returns
the payment status.

REST is a set of architectural style but not a protocol or a standard. API developers
can implement REST in a variety of ways. When a client request is made via a RESTful API, it
transfers a representation of the state of the resource to the requester or endpoint. This
information or representation is delivered in one of several formats like JSON or XML via HTTP
Protocol.

JSON is the most generally popular format to use because, despite its name, it’s language-
agnostic, as well as readable by both humans and machines.

REST API architecture that imposes conditions on how an API should work. REST was
initially created as a guideline to manage communication on a complex network like the
internet. You can use REST-based architecture to support high-performing and reliable
communication at scale. You can easily implement and modify it, bringing visibility and cross-
platform portability to any API system.

Clients: Clients are users who want to access information from the web. The client can
be a person or a software system that uses the API. For example, developers can write
programs that access weather data from a weather system. Or you can access the same data
from your browser when you visit the weather website directly.

Resources: Resources are the information that different applications provide to their
clients/users. Resources can be images, videos, text, numbers, or any type of data. The
machine that gives the resource to the client is also called the server. Organizations use APIs
to share resources and provide web services while maintaining security, control, and
authentication. In addition, APIs help them to determine which clients get access to specific
internal resources.

API developers can design APIs using several different architectures. APIs that follow the REST
architectural style are called REST APIs. Web services that implement REST architecture are
called RESTful web services. The term RESTful API generally refers to RESTful web APIs.
However, you can use the terms REST API and RESTful API interchangeably.

The following are some of the principles of the REST architectural style:

Uniform Interface: The uniform interface is fundamental to the design of any RESTful
webservice. It indicates that the server transfers information in a standard format. The
formatted resource is called a representation in REST. This format can be different from the
internal representation of the resource on the server application. For example, the server can
store data as text but send it in an HTML representation format.

Statelessness: In REST architecture, statelessness refers to a communication method in which


the server completes every client request independently of all previous requests. Clients can
request resources in any order, and every request is stateless or isolated from other requests.

274 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


This REST API design constraint implies that the server can completely understand and fulfil
the request every time.

Layered system: In a layered system architecture, the client can connect to other authorized
intermediate services between the client and server, and it will still receive responses from
the server. Sometimes servers can also pass on requests to other servers. You can design your
RESTful web service to run on several servers with multiple layers such as security,
application, and business logic, working together to fulfil client requests. These layers remain
invisible to the client. We can achieve this as part of Micro Services Design.

What are the benefits of RESTful APIs?

RESTful APIs include the following benefits:

Scalability: Systems that implement REST APIs can scale efficiently because REST optimizes
client-server interactions. Statelessness removes server load because the server does not
have to store past client request information.

Flexibility: RESTful web services support total client-server separation. Platform or


technology changes at the server application do not affect the client application. The ability
to layer application functions increases flexibility even further. For example, developers can
make changes to the database layer without rewriting the application logic.

Platform and Language Independence: REST APIs are platform and language independent,
meaning they can be consumed by a wide range of clients, including web browsers, mobile
devices, and other applications. As long as the client can send HTTP requests and understand
the response, it can interact with a REST API regardless of the technology stack used on the
server side. You can write both client and server applications in various programming
languages without affecting the API design. We can also change the technology on both sides
without affecting the communication.

Overall, REST APIs provide a simple, scalable, and widely supported approach to building web
services. These advantages in terms of simplicity, platform independence, scalability,
flexibility, and compatibility make REST as a popular choice for developing APIs in various
domains, from web applications to mobile apps and beyond.

How RESTful APIs work?

The basic function of a RESTful API is the same as browsing the internet. The client contacts
the server by using the API when it requires a resource. API developers explain how the client
should use the REST API in the server application with API documentation. These are the
general steps for any REST API call integration:

1. The client sends a request to the server. The client follows the API documentation to
format the request in a way that the server understands.
2. The server authenticates the client and Request and confirms that the client has the right
to make that request.
3. The server receives the request and processes it internally.

275 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


4. The server returns a response to the client. The response contains information that tells
the client whether the request was successful. The response also includes any information
that the client requested.

The REST API request and response details are vary slightly depending on how the API
developers implemented the API.

What does the RESTful API client request contain?

RESTful APIs require requests to contain the following main components:

URI (Unique Resource Identifier) : The server identifies each resource with unique
resource identifiers. For REST services, the server typically performs resource identification
by using a Uniform Resource Locator (URL). The URL specifies the path to the resource. A URL
is similar to the website address that you enter into your browser to visit any webpage. The
URL is also called the request endpoint and clearly specifies to the server what the client
requires.

HTTP Method: Developers often implements RESTful APIs by using the Hypertext Transfer
Protocol (HTTP). An HTTP method tells the server what it needs to do with the resource. The
following are four common HTTP methods:

• GET: Clients use GET to access resources that are located at the specified URL on
the server.
• POST: Clients use POST to send data to the server. They include the data
representation with the request body. Sending the same POST request multiple times
has the side effect of creating the same resource multiple times.

276 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


• PUT: Clients use PUT to update existing resources on the server. Unlike POST,
sending the same PUT request multiple times in a RESTful web service gives the same
result.
• DELETE: Clients use DELETE request to remove the resource.

HTTP Headers: Request headers are the metadata exchanged between the client and server.

Data: REST API requests might include data for the POST, PUT, and other HTTP methods to
work successfully.

Parameters: RESTful API requests can include parameters that give the server more details
about what needs to be done. The following are some different types of parameters:
• Path parameters that specify URL details.
• Query/Request parameters that request more information about the resource.
• Cookie parameters that authenticate clients quickly.

What does the RESTful API server response contain?

REST principles require the server response to contain the following main components:

Status line: The status line contains a three-digit status code that communicates request
success or failure.
2XX codes indicate success
4XX and 5XX codes indicate errors
3XX codes indicate URL redirection.

The following are some common status codes:


200: Generic success response
201: POST method success response as Created Resource
400: Incorrect/Bad request that the server cannot process
404: Resource not found

Message body: The response body contains the resource representation. The server selects
an appropriate representation format based on what the request headers contain i.e. like
JSON/XML formats. Clients can request information in XML or JSON formats, which define
how the data is written in plain text. For example, if the client requests the name and age of
a person named John, the server returns a JSON representation as follows:
{
"name":"John",
"age":30
}

Headers: The response also contains headers or metadata about the response. They
give more context about the response and include information such as the server, encoding,
date, and content type.

277 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


As per REST API creation Guidelines, we should choose HTTP methods depends on the
Database Operation performed by our functionality, as We discussed previously.

REST Services Implementation in Spring MVC:

Spring MVC is a popular framework for creating web applications in Java. Implementing
RESTful web services in Spring MVC involves using the Spring framework to create endpoints
that follow the principles of the REST architectural style. It can be used to create RESTful web
services, which are web services that use the REST architectural style.

RESTful services allow different software systems to communicate over the internet using
standard HTTP methods, like GET, POST, PUT, and DELETE. These services are based on a set
of principles that emphasize simplicity, scalability, and statelessness.

In REST Services implementation, Data will be represented as JOSN/XML type most of the
times. Now a days JSON is most popular data representational format to create and produce
REST Services.

So, we should know more about JSON.

JSON:
JSON stands for JavaScript Object Notation. JSON is a text format for storing and
transporting data. JSON is "self-describing" and easy to understand.

This example is a JSON string is :


{
"name":"John",
"age":30,
"car":null
}

JSON is a lightweight data-interchange format. JSON is plain text written in JavaScript object
notation. JSON is used to exchange data between multiple applications/services. JSON is
language independent.

JSON Syntax Rules:

JSON syntax is derived from JavaScript object notation syntax:


o Data is in name/value pairs
o Data is separated by commas
o Curly braces hold objects
o Square brackets hold arrays

278 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


A name/value pair consists of a field name (in double quotes), followed by a colon, followed
by a value:
Example: "name" : "John"

In JSON, values must be one of the following data types:

o a string
o a number
o an object
o an array
o a Boolean
o null

JSON vs XML:

Both JSON and XML can be used to receive data from a web server. The following JSON and
XML examples both define an employee’s object, with an array of 3 employees:

JSON Example

{
"employees": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Anna",
"lastName": "Smith"
},
{
"firstName": "Peter",
"lastName": "Jones"
}
]
}

XML Example:

<employees>
<employee>
<firstName>John</firstName>
<lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName>

279 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


<lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName>
<lastName>Jones</lastName>
</employee>
</employees>

JSON is Like XML Because

• Both JSON and XML are "self-describing" (human readable)


• Both JSON and XML are hierarchical (values within values)
• Both JSON and XML can be parsed and used by lots of programming languages

When A Request Body Contains JSON/XML data Format, then how Spring MVC/JAVA
language handling Request data?

Here, We should Convert JSON/XML data to JAVA Object while Request landing on Controller
method, after that we are using JAVA Objects in further process. Similarly, Sometimes we have
to send Response back as either JSON or XML format i.e. JAVA Objects to JSON/XML Format.

For these conversions, we have few pre-defined solutions in Market like Jackson API, GSON
API, JAXB etc..

JSON to JAVA Conversion:


Spring MVC supports Jackson API which will take care of un-marshalling/mapping JSON
request body to Java objects. We should add Jackson API dependencies explicitly In Spring
MVC, If It is Spring Boot MVC application Jackson API jars will be added internally. We can use
@RequestBody Spring MVC annotation to deserialize/un-marshal JSON string to Java object.
Similarly, java method return data will be converted to JSON format i.e. Response of Endpoint
by using an annotation @ResponseBody.

And as you have annotated with @ResponseBody of endpoint method, we no need to do


explicitly JAVA to JSON conversion. Just return a POJO and Jackson serializer will take care of
converting to Json format. It is equivalent to using @ResponseBody when used with
@Controller. Rather than placing @ResponseBody on every controller method we place
@RestController instead of @Controller and @ResponseBody by default is applied on all
resources in that controller.

Note: we should carte Java POJO classes specific to JSON payload structure, to enable auto
conversion between JAVA and JSON.

280 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


JSON with Array of String values:

JSON Payload: Below Json contains ARRY of String Data Type values

{
"student":[
"Dilip",
"Naresh",
"Mohan",
"Laxmi"
]
}

Java Class: JSON Array of String will be takes as List<String> with JSON key name.

import java.util.List;

public class StudentDetails {

private List<String> student;

public List<String> getStudent() {


return student;
}
public void setStudent(List<String> student) {
this.student = student;
}
@Override
public String toString() {
return "StudentDetails [student=" + student + "]";
}
}

281 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


JSON payload with Array of Student Object Values:

Below JSON payload contains array of Student values.

{
"nareshIt": {
"students": [
{
"no": "1",
"name": "Dilip",
"mobile": 8826111377
},
{
"no": "2",
"name": "Naresh",
"mobile": 8125262702
}
]
}
}

Below picture showing how are creating JAVA classes from above payload.

Created Three java files to wrap above JSON payload structure:

Student.java

public class Student {

282 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


private String no;
private String name;
private long mobile;

//Setters and Getters


}
Add Student as List in class NareshIt.java

import java.util.ArrayList;
public class NareshIt {
private ArrayList<Student> students;

//Setters and Getters

StudentsData.java

public class StudentsData {


public NareshIt nareshIt;

//Setters and Getters


}

Now we will use StudentsData class to bind our JSON Payload.

➢ Let’s Take another Example of JSON to JAVA POJO class:

JSON PAYLOAD: Json with Array of Student Objects

{
"student": [
{
"firstName": "Dilip",
"lastName": "Singh",
"mobile": 88888,
"pwd": "Dilip",
"emailID": "Dilip@Gmail.com"
},
{
"firstName": "Naresh",
"lastName": "It",
"mobile": 232323,
"pwd": "Naresh",
"emailID": "Naresh@Gmail.com"
}
]

283 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}

For the above Payload, JAVA POJO’S are:

import com.fasterxml.jackson.annotation.JsonProperty;

public class StudentInfo {

private String firstName;


private String lastName;
private long mobile;
private String pwd;
@JsonProperty("emailID")
private String email;

//Setters and Getters


}

Another class To Wrap above class Object as List with property name student as per JSON.

import java.util.List;

public class Students {

List<StudentInfo> student;

public List<StudentInfo> getStudent() {


return student;
}
public void setStudent(List<StudentInfo> student) {
this.student = student;
}
}

From the above JSON payload and JAVA POJO class, we can see a difference for one JSON
property called as emailID i.e. in JAVA POJO class property name we taken as email instead
of emailID. In Such case to map JSON to JAVA properties with different names, we use an
annotation called as @JsonProperty("jsonPropertyName").

@JsonProperty:
The @JsonProperty annotation is used to specify the property name in a JSON object
when serializing or deserializing a Java object using the Jackson API library. It is often used
when the JSON property name is different from the field name in the Java object, or when
the JSON property name is not in camelCase.

284 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


If you want to serialize this object to JSON and specify that the JSON property names should
be "first_name", "last_name", and "age", you can use the @JsonProperty annotation like this:

public class Person {


@JsonProperty("first_name")
private String firstName;
@JsonProperty("last_name")
private String lastName;
@JsonProperty
private int age;

// getters and setters go here


}

As a developer, we should always create POJO classes aligned to JSON payload to bind JOSN
data to Java Object with @RequestBody annotation.

To implement REST services in Spring MVC, you can use the @RestController annotation. This
annotation marks a class as a controller that returns data to the client in a RESTful way.

@RestController:

Spring introduced the @RestController annotation in order to simplify the creation of


RESTful web services. @RestController is a specialized version of the controller. It's a
convenient annotation that combines @Controller and @ResponseBody, which eliminates
the need to annotate every request handling method of the controller class with the
@ResponseBody annotation.
Package: org.springframework.web.bind.annotation.RestController;
For example, When we mark class with @Controller and we will use @ResponseBody at
request mapping method level.

@RestController = @Controller + @ResponseBody

@Controller
public class MAcBookController {

@GetMapping(path = "/mac/details")
@ResponseBody

285 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


public String getMacBookDetail() {
return "MAC Book Details : Price 200000. Model 2022";
}

@GetMapping(path = "/iphone/details")
@ResponseBody
public String getIphoneDetail() {
return "Iphone Details : Price 150000. Model 15 Pro";
}
}

➢ If we Used @RestController with controller class, removed @ResponseBody at all handler


mapping methods level.

@RestController
public class MAcBookController {

@GetMapping(path = "/mac/details")
public String getMacBookDetail() {
return "MAC Book Details : Price 200000. Model 2022";
}

@GetMapping(path = "/iphone/details")
public String getIphoneDetail() {
return "Iphone Details : Price 150000. Model 15 Pro";
}
}

That’s all, @RestController is just like a shortcut annotation to avoid declaring


@ResponseBody on every controller handler mapping method inside a class.

@RequestBody Annotation:

The @RequestBody annotation in Spring is used to bind the HTTP request body to a
method parameter. This means that Spring will automatically deserialize the request body
into a Java object and that object is then passed to the method as a parameter. The
@RequestBody annotation can be used on controller methods.

For example, the following controller method accepts a User object as a parameter:

@PostMapping("/users")
public User createUser(@RequestBody User user) {
// ...

286 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}

➢ When you send a POST request to the /users endpoint with a JSON body containing the
user data, Spring will automatically deserialize the JSON into a User object and pass it to
the createUser() method.

➢ The @RequestBody annotation is a powerful tool that makes it easy to work with HTTP
request bodies in Spring. It is especially useful for developing REST APIs.

Here are some additional things to keep in mind about the @RequestBody annotation:

• The request body must be in a supported media type, such as JSON, XML.
• Spring will use an appropriate HTTP message converter to deserialize the request body.
• If the request body cannot be deserialized, Spring will throw
a HttpMessageNotReadableException.

Postman API Testing Tool:

Postman is a popular and widely used API (Application Programming Interface) testing
and development tool. It provides a user-friendly interface for sending HTTP requests to APIs
and inspecting the responses. Postman offers a range of features that make it valuable for
developers, testers, and anyone working with APIs:

Some of the key features of Postman API Tools include:

• API client: Postman provides a powerful API client that allows you to send HTTP requests
to any API and inspect the responses. The API client supports a wide range of
authentication protocols and response formats.
• API testing: Postman provides a powerful API testing framework that allows you to create
and execute tests for your APIs. Postman tests can be used to validate the functionality,
performance, and security of your APIs.
• API design: Postman can be used to design your API specifications in OpenAPI, RAML,
GraphQL, or SOAP formats. Postman's schema editor makes it easy to work with
specification files of any size, and it validates specifications with a built-in linting engine.

287 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


• API documentation: Postman can be used to generate documentation for your APIs in a
variety of formats, including HTML, Markdown, and PDF. Postman documentation is
automatically generated from your API requests, so it is always up-to-date.
• API monitoring: Postman can be used to monitor your APIs for performance and
availability issues. Postman monitors can be configured to send alerts when your APIs are
unavailable or when they are not performing as expected.
Postman is a powerful tool that can help you to streamline your API development workflow.
It is used by developers and teams of all sizes to build, test, document, and monitor APIs.

Here are some examples of how Postman API Tools can be used:

• A developer can use Postman to explore a new API and learn how to use it.
• A QA engineer can use Postman to create and execute tests for an API.
• A DevOps engineer can use Postman to monitor an API for performance and availability
issues.
• A product manager can use Postman to generate documentation for an API.
• A sales engineer can use Postman to demonstrate an API to a customer.

Project Setup:

1. Create Spring Boot Web Module Project


2. Now Create an endpoints or REST Services for below requirement.

Requirement: Write a Rest Service for User Registration. User Details Should Be :

• User Name
• Email Id
• Mobile
• Password

• Create a JSON Mapping for above Requirement with dummy values.

{
"name" : "Dilip",
"email" : "dilip@gmail.com",
"mobile" : "+91 73777373",
"password" : "Dilip123"
}

288 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


3. Before Creating Controller class, we should Create JAVA POJO class which is compatible
with JSON Request Data. So create a JAVA class, as discussed previously. Which is
Responsible for holding Request Data of JSON.

package com.swiggy.user.request;

public class UserRegisterRequest {

private String name;


private String email;
private String mobile;
private String password;

public String getName() {


return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getPassword() {

289 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


return password;
}
public void setPassword(String password) {
this.password = password;
}
}

4. Now Create A controller and inside an endpoint for User Register Request Handling.

package com.swiggy.user.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.swiggy.user.request.UserRegisterRequest;

@RestController
@RequestMapping("/user")
public class UserController {

@PostMapping("/register")
public String getUserDetails(@RequestBody UserRegisterRequest request) {
System.out.println(request.getEmail());
System.out.println(request.getName());
System.out.println(request.getPassword());
return "User Created Successfully";
}
}

In Above, We are used @RequestBody for binding/mapping incoming JSON request to


JAVA Object at method parameter layer level. Means, Spring MVC internally maps JSON to
JAVA with help of Jackson API jar files.

5. Deploy Your Application in Server Now. After Deployment we have to Test now weather it
Service is working or not.

6. Now We are Taking Help of Postman to do API/Services Testing.

o Open Postman
o Now Click on Add request
o Select Your Service HTTP method
o And Enter URL of Service
o Select Body
o Select raw
o Select JSON
o Enter JSON Body as shown in Below.

290 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


After Clicking on Send Button, Summited Request to Spring MVC REST Service
Endpoint method and we got Response back with 200 Ok status Code.

In Below, We can See in Server Console, Request Data is printed what we Received
from Client/Postman level as JSON data.

291 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Path Variables:
Path variable is a template variable called as place holder of URI, i.e. this variable path
of URI. @PathVariable annotation can be used to handle template variables in the request
URI mapping, and set them as method parameters. Let's see how to use @PathVariable and
its various attributes. We will define path variable as part of URI in side curly braces{}.

Package of Annotation: org.springframework.web.bind.annotation.PathVariable;

Examples:
URI with Template Path variables : /location/{locationName}/pincode/{pincode}
URI with Data replaced : /location/Hyderabad/pincode/500072

Example for endpoint URI mapping in Controller : /api/employees/{empId}

@GetMapping("/api/employees/{empId}")
public String getEmployeesById(@PathVariable(“empId”) String empId) {

return "Employee ID: " + empId;


}

Example 2: Path variable Declaration

292 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Requirement : Get User Details with User Email Id.

In these kind of requirements, like getting Data with Resource ID’s. We can Use Path Variable
as part of URI instead of JSON mapping and equivalent Request Body classes. So Create a
REST endpoint with a Path Variable of Email ID.

UserController.java : Add Below Logic In existing User Controller.

@RequestMapping(value = "/get/{emailId}", method = RequestMethod.GET)


public UserRegisterResponse getUserByEmailId(@PathVariable("emailId") String email) {
return userService.getUserDetails(email);
}

➢ Now Add Method in Service Class for interacting with Repository Layer.

Method inside Service Class : UserService.java

public UserRegisterResponse getUserDetails(String email) {


SwiggyUsers user = repository.findById(email).get();
//Entity Object to DTO object
UserRegisterResponse response = new UserRegisterResponse();
response.setEmail(user.getEmail());
response.setMobile(user.getMobile());
response.setName(user.getName());
return response;
}

Testing: Pass Email Value in place of PATH variable

293 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Multiple Path Variable as part of URI:
We can define more than one path variables as part of URI, then equal number of
method parameters with @PathVaribale annotation defined in handler mapping method.

NOTE: We no need to define value inside @PathVariable when we are taking method
parameter name as it is URI template/Path variable.

Syntax : /{pathvar1}/{pathvar2}
Example: /pharmacy/{location}/pincode/{pincode}

Requirement : Add Order Details as shown in below.


• Order ID
• Order status
• Amount
• Email Id
• City

After adding Orders, Please Get Order Details based on Email Id and Order Status.

In this case, we are passing values of Email ID and Order Status to find out Order Details. Now
we can take Path variables here to fulfil this requirement.

➢ Create an endpoints for adding Order Details and Getting Order Details with Email ID
and Order Status.

Create Request, Response and Entity Classes.

OrderRequest.java

package com.swiggy.order.request;

public class OrderRequest {

private String orderID;


private String orderstatus;
private double amount;
private String emailId;
private String city;

public String getOrderID() {


return orderID;
}
public void setOrderID(String orderID) {
this.orderID = orderID;
}
public String getOrderstatus() {
return orderstatus;

294 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}
public void setOrderstatus(String orderstatus) {
this.orderstatus = orderstatus;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}

➢ OrderResponse.java

package com.swiggy.order.response;

public class OrderResponse {

private String orderID;


private String orderstatus;
private double amount;
private String emailId;
private String city;

public OrderResponse() {
}
public OrderResponse(String orderID, String orderstatus, double amount,
String emailId, String city) {
this.orderID = orderID;
this.orderstatus = orderstatus;
this.amount = amount;
this.emailId = emailId;
this.city = city;
}
public String getOrderID() {

295 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


return orderID;
}
public void setOrderID(String orderID) {
this.orderID = orderID;
}
public String getOrderstatus() {
return orderstatus;
}
public void setOrderstatus(String orderstatus) {
this.orderstatus = orderstatus;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}

➢ Entity Class : SwiggyOrders.java

package com.swiggy.order.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "swiggy_orders")
public class SwiggyOrders {

@Id
@Column
private String orderID;

296 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@Column
private String orderstatus;
@Column
private double amount;
@Column
private String emailId;
@Column
private String city;

public String getOrderID() {


return orderID;
}
public void setOrderID(String orderID) {
this.orderID = orderID;
}
public String getOrderstatus() {
return orderstatus;
}
public void setOrderstatus(String orderstatus) {
this.orderstatus = orderstatus;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}

➢ Controller class : OrderController.java

package com.swiggy.order.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;

297 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.swiggy.order.request.OrderRequest;
import com.swiggy.order.response.OrderResponse;
import com.swiggy.order.service.OrderService;

@RestController
@RequestMapping("/order")
public class OrderController {

@Autowired
OrderService orderService;

@PostMapping(value = "/create")
public String createOrder(@RequestBody OrderRequest request) {
return orderService.createOrder(request);
}

@GetMapping("/email/{emailId}/status/{status}")
public List<OrderResponse> getOrdersByemaailIDAndStaus(@PathVariable String
emailId, @PathVariable("status") String orderStaus ){
List<OrderResponse> orders =
orderService.getOrdersByemaailIDAndStaus(emailId, orderStaus);

return orders;
}
}

➢ Now create methods in Service layer.

package com.swiggy.order.service;

import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.swiggy.order.entity.SwiggyOrders;
import com.swiggy.order.repository.OrderRepository;
import com.swiggy.order.request.OrderRequest;
import com.swiggy.order.response.OrderResponse;

@Service
public class OrderService {

298 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@Autowired
OrderRepository reposity;

public String createOrder(OrderRequest request) {


SwiggyOrders order = new SwiggyOrders();
order.setAmount(request.getAmount());
order.setCity(request.getCity());
order.setEmailId(request.getEmailId());
order.setOrderID(request.getOrderID());
order.setOrderstatus(request.getOrderstatus());
reposity.save(order);
return "Order Creeated Successfully";
}

public List<OrderResponse> getOrdersByemaailIDAndStaus(String emailId,


String orderStaus) {
List<SwiggyOrders> orders =
reposity.findByEmailIdAndOrderstatus(emailId , orderStaus);

List<OrderResponse> allOrders = orders.stream().map(


v -> new OrderResponse(
v.getOrderID(),
v.getOrderstatus(),
v.getAmount(),
v.getEmailId(),
v.getCity()
)).collect(Collectors.toList());

return allOrders;
}
}

➢ Create Repository : OrderRepository.java

Add JPA Derived Query findBy() Method for Email Id and Order Status.

package com.swiggy.order.repository;

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.swiggy.order.entity.SwiggyOrders;

@Repository
public interface OrderRepository extends JpaRepository<SwiggyOrders, String>{
List<SwiggyOrders> findByEmailIdAndOrderstatus(String emailId, String orderStaus);

299 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


}

From Postman Test end point: URL formation, replacing Path variables with real values

➢ We can also handle more than one Path Variables of URI by using a method parameter
of type java.util.Map<String, String>.

@GetMapping("/pharmacy/{location}/pincode/{pincode}")
public String getPharmacyByLocationAndPincode(@PathVariable Map<String, String>
values) {
String location = values.get("location"); // Key is Path variable
String pincode = values.get("pincode");

return "Location Name : " + location + ", Pin code: " + pincode;
}

Query String and Query Parameters:

Query string is a part of a uniform resource locator (URL) that assigns values to
specified parameters. A query string commonly includes fields added to a base URL by a Web
browser or other client application. Let’s understand this statement in a simple way by an
example. Suppose we have filled out a form on websites and if we have noticed the URL
something like as shown below as follows:

300 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


http://internet.org/process-homepage?number1=23&number2=12

So in the above URL, the query string is whatever follows the question mark sign (“?”) i.e
(number1=23&number2=12) this part. And “number1=23”, “number2=12” are Query
Parameters which are joined by a connector “&”.

Let us consider another URL something like as follows:


http://internet.org?title=Query_string&action=edit

So in the above URL, the query string is “title=Query_string&action=edit” this part. And
“title=Query_string”, “action=edit” are Query Parameters which are joined by a connector
“&”.

Now we are discussing the concept of the query string and query parameter from the Spring
MVC point of view. Developing Spring MVC application and will understand how query strings
and query parameters are generated.

@RequestParam:
In Spring, we use @RequestParam annotation to extract the id of query parameters. Assume
we have Users Data, and we should get data based on email Id.

Example : URL : /details?email=<value-of-email>

@GetMapping("/details")
public String getUserDetails(@RequestParam String email) {
//Now we can pass Email Id to service layer to fetch user details
return "Email Id of User : " + email;
}

Example with More Query Parameters :

Requirement: Please Get User Details by using either email or mobile number

Method in controller:

@GetMapping("/details")
public List<Users> getUsersByEmailOrMobile(@RequestParam String email,
@RequestParam String mobileNumber) {

//Now we can pass Email Id and Mobile Number to service layer to fetch user details
List<Users> response = service.getUsersByEmailOrMobile(email, mobileNumber);
return response;
}

NOTE: Add Service, Repository layers.

URI with Query Params: details?email=<value>&mobileNumber=<value>

301 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Note: By Default every Request Parameter variable is Required i.e. we should pass Query
Parameter and its value as part of URL always. If we are missed any parameter, then we will
get bad request.

302 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


If we want to make sure any request parameter as optional, then we have to use attribute
required=false in side @RequestParam annotation. Now let’s make Request Parameter
mobileNumber as an Optional in controller.

@GetMapping("/details")
public List<Users> getUsersByEmailOrMobile(@RequestParam String email,
@RequestParam(required = false) String mobileNumber) {

List<Users> response = service.getUsersByEmailOrMobile(email, mobileNumber);


return response;
}

Testing Endpoint: Now mobileNumber Request Parameter is missing in URI, but still our
endpoint is working only with one Request parameter email.

Mapping a Multi-Value Parameter: A single @RequestParam can have multiple values:

@GetMapping("/api")
@ResponseBody
public String getUsers(@RequestParam List<String> id) {
return "IDs are " + id;
}

303 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


And Spring MVC will map a comma-delimited id parameter:

URI: /api?id=1,2,3

Or we can pass a list of separate id parameters as part of URL

URI : /api?id=1&id=2

Mapping All Parameters:

We can also have multiple parameters without defining their names or count by just using
a Map:

@GetMapping("/api")
public String getUsers(@RequestParam Map<String,String> allParams) {
return "Parameters are " + allParams.entrySet();
}

Now we can read all Request Params from Map Object as Key and Value Pairs and we will
utilize as per requirement.

When to use Query Param vs Path Variable:

As a best practice, almost of developers are recommending following way. If you want
to identify a resource, you should use Path Variable. But if you want to sort or filter items on
data, then you should use query parameters. So, for example you can define like this:

/users # Fetch a list of users


/users?occupation=programmer&skill=java # Fetch a list of java programmers

/users/123 # Fetch a user who has id 123

Swagger UI With SpringBoot Applications:

“Swagger is a set of rules, specifications and tools that help us document our APIs.”
“By using Swagger UI to expose our API’s documentation, we can save significant
time.”
Swagger UI allows anyone — be it your development team or your end consumers — to
visualize and interact with the API’s resources without having any of the implementation logic in place.
It’s automatically generated from your OpenAPI (formerly known as Swagger) Specification, with the
visual documentation making it easy for back end implementation and client side consumption.

Swagger UI is one of the platform’s attractive tools. In order for documentation to be useful,
we will need it to be browsable and to be perfectly organized for easy access. It is for this reason that
writing good documentation may be tedious and use a lot of the developers’ time.

304 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Create Spring Boot Web Application:

1. Open STS -> File-> New > Spring Starter Project

2. Fill All Project details as shown below and click on Next.

305 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


3. In Next Page, Add Spring Boot Modules/Starters as shown below and click on finish.
NOTE: Spring Web is mandatory, because REST Service Documentation we should do with
Swagger.

4. After Project Creation, Open pox.xml file and add below dependency starter in side
dependencies section and save.

<!--Swagger/OpenAPI Documentation starter-->

<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.1.0</version>
</dependency>

306 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


5. Now open application.properties file and add below two properties and save. With these
properties application started on port : 5566 with context path '/user'.

server.port=5566
server.servlet.context-path=/user

6. Now start your spring Boot application

7. Enter URL in Browser for OpenAPI Swagger Documentation of Web services. Then you can
Swagger UI page with empty Services List. Because Our application not contained any web
services.

NOTE: The Swagger UI page will then be available at http://server:port/context-


path/swagger-ui.html and the OpenAPI description will be available at the following URL for
JSON format: http://server:port/context-path/v3/api-docs. Documentation can be available
in YAML format as well, on the following path : /v3/api-docs.yaml

server: The server name, hostname or IP


port: The server port
context-path: The context path of the application

Swagger UI URL : http://localhost:5566/user/swagger-ui/index.html

307 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Successfully Our SpringBoot Application Integrated with OpenAPI/Swagger documentation.

Adding REST Services to our application, to see Swagger API documentation:

Now Create A controller Class in Our Application : UserController.java


Adding Fe REST Services inside controller class.

package com.tek.teacher.user.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

@RequestMapping(method=RequestMethod.POST, path = "/create")


public String createUser(@RequestBody CreateUserRequest request) {
return "User Created Successfully ";
}

@RequestMapping(method=RequestMethod.GET, path = "/id/{userID}")


public CreateUserResponse createUser(@PathVariable String userID) {

System.out.println("Loading Values of user : " + userID);

308 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


CreateUserResponse response = new CreateUserResponse();
response.setEmail("Tekk.Teacher@gmail.com");
response.setFirstName("Tek");
response.setLastName("Teacher");

return response;
}
}

➢ Create Request and Response DTO classes: CreateUserRequest.java

package com.tek.teacher.user.controller;

public class CreateUserRequest {

private String firstName;


private String lastName;
private String email;
private String password;
private long mobile;
private float income;
private String gender;

public String getFirstName() {


return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public long getMobile() {

309 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


return mobile;
}
public void setMobile(long mobile) {
this.mobile = mobile;
}
public float getIncome() {
return income;
}
public void setIncome(float income) {
this.income = income;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}

CreateUserResponse.java

package com.tek.teacher.user.controller;

public class CreateUserResponse {

private String firstName;


private String lastName;
private String email;
private long mobile;
private float income;
private String gender;

public String getFirstName() {


return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}

310 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


public void setEmail(String email) {
this.email = email;
}
public long getMobile() {
return mobile;
}
public void setMobile(long mobile) {
this.mobile = mobile;
}
public float getIncome() {
return income;
}
public void setIncome(float income) {
this.income = income;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}

Now Start Your Spring Boot App. After application started, Now please enter swagger URL in
browser. You can see all endpoints/services API request and response format Data.

Swagger UI URL : http://localhost:5566/user/swagger-ui/index.html

311 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ You can expand above both endpoints and look for payload details.

We can Test API calls from Swagger UI, Please click on Try it Out button then it will you
pass values to parameters/properties. In Below, I am passing userId value in GET API
service and then click on Execute.

312 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


After clicking on Execute You will get Response in response Section.

This is how we can integrate and use swagger UI API Documentation Tool with our
applications to share all REST API data in UI format.

313 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Spring Boot – application.yml / application.yaml File:

In Spring Boot, whenever we create a new Spring Boot Application in spring starter, or inside
an IDE (Eclipse or STS) a file is located inside the src/main/resources folder named
as application.properties file.

So in a spring boot application, application.properties file is used to write the application-


related property into that file. This file contains the different configuration values which is
required to run the application. The type of property like changing the port, database
connectivity and many more.

In place of properties file, we can use YAML/YML based configuration files to achieve same
behaviour.
What is this YAML/YML file?
YAML stands for Yet Another Markup Language. YAML is a data serialization language
that is often used for writing configuration files. So YAML configuration file in Spring Boot
provides a very convenient syntax for storing logging configurations in a hierarchical format.
The application.properties file is not that readable. So most of the time developers choose
application.yml file over application.properties file. YAML is a superset of JSON, and as such
is a very convenient format for specifying hierarchical configuration data. YAML is more
readable and it is good for the developers to read/write configuration files.

• Comments can be identified with a pound or hash symbol (#). YAML does not support
multi-line comment, each line needs to be suffixed with the pound character.
• YAML files use a .yml or .yaml extension, and follow specific syntax rules.

Now let’s see some examples for better understanding :

314 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


If it is application.properties file :

server.port=4343
server.servlet.context-path=/gmail
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.username=c##dilip
spring.datasource.password=dilip
spring.jpa.show-sql=true

If we written same properties content in application.yml:

Similarly, we can add all other Properties in same format always as per YAML scriprt rules
and regulations.
Now we can start our Spring Boot application as usual and continue development and
testing activities.

HTTP status codes in building RESTful API’s:

HTTP status codes are three-digit numbers that are returned by a web server in response to a
client's request made to a web page or resource. These codes indicate the outcome of the
request and provide information about the status of the communication between the client
(usually a web browser) and the server. They are an essential part of the HTTP (Hypertext
Transfer Protocol) protocol, which is used for transferring data over the internet. HTTP defines
these standard status codes that can be used to convey the results of a client’s request.

315 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


The status codes are divided into five categories.

Status Codes Series Description


1xx: Informational Communicates transfer protocol-level information.
2xx: Success Indicates that the client’s request was accepted successfully.
3xx: Redirection Indicates that clients must take some additional action in order
to complete their request.
4xx: Client Error This category of error status codes points the finger at clients.
5xx: Server Error The server takes responsibility for these error status codes.

Some of HTTP status codes summary being used mostly in REST API creation

1xx Informational:
This series of status codes indicates informational content. This means that the
request is received and processing is going on. Here are the frequently used informational
status codes:

100 Continue:
This code indicates that the server has received the request header and the client can
now send the body content. In this case, the client first makes a request (with the Expect:
100-continue header) to check whether it can start with a partial request. The server can then
respond either with 100 Continue (OK) or 417 Expectation Failed (No) along with an
appropriate reason.

101 Switching Protocols:


This code indicates that the server is OK for a protocol switch request from the client.

316 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


102 Processing:
This code is an informational status code used for long-running processing to prevent
the client from timing out. This tells the client to wait for the future response, which will have
the actual response body.

2xx Success:
This series of status codes indicates the successful processing of requests. Some of the
frequently used status codes in this class are as follows.

200 OK:
This code indicates that the request is successful and the response content is returned
to the client as appropriate.

201 Created:
This code indicates that the request is successful and a new resource is created.

204 No Content:
This code indicates that the request is processed successfully, but there's no return
value for this request. For instance, you may find such status codes in response to the deletion
of a resource.
3xx Redirection:
This series of status codes indicates that the client needs to perform further actions
to logically end the request. A frequently used status code in this class is as follows.

304 Not Modified:


This status indicates that the resource has not been modified since it was last
accessed. This code is returned only when allowed by the client via setting the request
headers as If-Modified-Since or If-None-Match. The client can take appropriate action on the
basis of this status code.

4xx Client Errors:


This series of status codes indicates an error in processing the request. Some of the
frequently used status codes in this class are as follows:

400 Bad Request:


This code indicates that the server failed to process the request because of the
malformed syntax in the request. The client can try again after correcting the request.
401 Unauthorized:
This code indicates that authentication is required for the resource. The client can try
again with appropriate authentication.

403 Forbidden:
This code indicates that the server is refusing to respond to the request even if the
request is valid. The reason will be listed in the body content if the request is not a HEAD
method.

317 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


404 Not Found:
This code indicates that the requested resource is not found at the location specified
in the request.

405 Method Not Allowed:


This code indicates that the HTTP method specified in the request is not allowed on
the resource identified by the URI.

408 Request Timeout:


This code indicates that the client failed to respond within the time window set on the
server.

409 Conflict:
This code indicates that the request cannot be completed because it conflicts with
some rules established on resources, such as validation failure.

5xx Server Errors:


This series of status codes indicates server failures while processing a valid request.
Here is one of the frequently used status codes in this class:

500 Internal Server Error:


This code indicates a generic error message, and it tells that an unexpected error
occurred on the server and that the request cannot be fulfilled.

501 (Not Implemented):


The server either does not recognize the request method, or it cannot fulfil the
request. Usually, this implies future availability (e.g., a new feature of a web-service API).

REST API Specific HTTP Status Codes:

Generally we will have likewise below scenarios and respective status codes in REST API
services. For Example,

POST - Create : 201 Created : Successfully Request Completed.

PUT - Update : 200 Ok : Successfully Updated Data


If not i.e. Resource Not Found Data
404 Not Found : Successfully Processed but Data Not available

GET - Read : 200 Ok : Successfully Retrieved Data


If not i.e. Resource Not Found Data
404 Not Found : Successfully Processed but Data Not available

DELETE - Delete : 204 No Content: Successfully Deleted Data


If not i.e. Resource Not Found Data
404 Not Found : Successfully Processed but Data Not available

318 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Binding HTTP status codes and Response in Spring:

To bind response data and relevant HTTP status code with endpoint in side controller class,
we will use predefined Spring provided class ResponseEntity.

ResponseEntity:
ResponseEntity represents the whole HTTP response: status code, headers, and body.
As a result, we can use it to fully configure the HTTP response. If we want to use it, we have
to return it from the endpoint, Spring takes care of the rest. ResponseEntity is a generic type.
Consequently, we can use any type as the response body. This will be used in Controller
methods as well as in RestTemplate.

This can be used as return value from an Controller URI method:

@RequestMapping("/handle")
public ResponseEntity<T> handle() {
// Logic
return new ResponseEntity<T>(ResponseData, ResponseHeaders, StatusCode);
}

Points to be noted:

1. We should Define ResponseEntity<T> with Response Object Data Type at method


declaration as Return type of method.
2. We should bind actual Response Data Object with Http Status Codes by passing as
Constructor Parameters of ResponseEntity class, and then we returning that
ResponseEntity Object to HTTP Client.

Few Examples of Controller methods with ResponseEntity:

@RestController
public class NetBankingController {

@PostMapping("/create")
@ResponseStatus(value = HttpStatus.CREATED) //Using Annotation
public String createAccount(@Valid @RequestBody AccountDetails accountDetails) {

return "Created Net banking Account. Please Login.";


}

@PostMapping("/create/loan") //Using Class


public ResponseEntity<String> createLoan(@Valid @RequestBody AccountDetails details) {

return new ResponseEntity<>("Created Loan Account.", HttpStatus.CREATED);


}
}

319 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Another Example:

@RestController
public class OrdersController {

@RequestMapping(value = "/product/order", method = RequestMethod.PUT)


public ResponseEntity<String> updateOrders(@RequestBody OrderUpdate request) {

String result = orderService. updateOrders(request);


if (result.equalsIgnoreCase("Order ID Not found")) {
return new ResponseEntity<String>(result, HttpStatus.NOT_FOUND);
}
return new ResponseEntity<String>(result, HttpStatus.OK);
}
}

@GetMapping("/orders")
public ResponseEntity<Order> getOrders(@RequestParam("orderID") String orderID) {
Order response = service.getOrders(orderID);
return new ResponseEntity<Order>( response, HttpStatus.OK);
}
}

This is how can write any Response Status code in REST API Service implementation.
Please refer RET API Guidelines for more information at what time which HTTP status code
should be returned to client.

Headers in Spring MVC:


HTTP headers are part of the Hypertext Transfer Protocol (HTTP), which is the
foundation of data communication on the World Wide Web. They are metadata or key-value
pairs that provide additional information about an HTTP request or response. Headers are
used to convey various aspects of the communication between a client (typically a web
browser) and a server.

HTTP headers can be classified into two main categories: request headers and response
headers.

Request Headers:
Request headers are included in an HTTP request sent by a client to a server. They provide
information about the client's preferences, the type of data being sent, authentication
credentials, and more. Some common request headers include:

• User-Agent: Contains information about the user agent (usually a web browser)
making the request.
• Accept: Specifies the media types (content types) that the client can process.

320 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


• Authorization: Provides authentication information for accessing protected
resources.
• Cookie: Sends previously stored cookies back to the server.
• Content-Type: Specifies the format of the data being sent in the request body.

Response Headers:

Response headers are included in an HTTP response sent by the server to the client. They
convey information about the server's response, the content being sent, caching directives,
and more. Some common response headers include:
• Content-Type: Specifies the format of the data in the response body.
• Content-Length: Specifies the size of the response body in bytes.
• Set-Cookie: Sets a cookie in the client's browser for managing state.

HTTP headers are important for various purposes, including negotiating content types,
enabling authentication, handling caching, managing sessions, and more. They allow both
clients and servers to exchange additional information beyond the basic request and response
data. Proper understanding and usage of HTTP headers are essential for building efficient and
secure web applications.

Spring MVC provides mechanisms to work with HTTP headers both in requests and responses.
Here's how you can work with HTTP headers in Spring MVC.

Handling Request Headers:

Accessing Request Headers: Spring provides the @RequestHeader annotation that allows
you to access specific request headers in your controller methods. You can use this annotation
as a method parameter to extract header values.

In Spring Framework's MVC module, @RequestHeader is an annotation used to extract values


from HTTP request headers and bind them to method parameters in your controller methods.
This annotation is part of Spring's web framework and is commonly used to access and work
with the values of specific request headers.

@GetMapping("/endpoint")
public ResponseEntity<String> handleRequest(@RequestHeader("Header-Name") String
headerValue) {
// Do something with the header and other values

321 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Example: Define a header user-name inside request:

➢ Header and its Value should come from Client while they are triggering this endpoint.

package com.flipkart.controller;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;

@RestController
public class OrderController {
//Header is Part of Request, i.e. Should be Come from Client Side.
@GetMapping("/data")
public String testHeaders(@RequestHeader("user-name") String userName) {
return "Connected User : " + userName;
}
}

Testing: Without Sending Header and Value from Client, Sending Request to Service.

Result : We Got Bad request like Header is Missing i.e. Header is Mandatory by default if
we defined in Controller method.

Setting Header in Client: i.e. In Our Case From Postman:


In Postman, Add header user-name and its value under Headers Section. Now request is
executed Successfully.

322 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Optional Headers:
If we want to make Header as an Optional i.e. non mandatory. we have to add an attribute
of required and Its value as false.

package com.flipkart.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class OrderController {

//Header is Part of Request, i.e. Should be Come from Client Side.


@GetMapping("/data")
public String testHeaders(@RequestHeader(name = "user-name",
required = false) String userName) {
return "Connected User : " + userName;
}
}

Testing:
➢ No header Added, So Header value is null.

323 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Default Value Of Header:
➢ We can Set Header Default Value also in case if we are not getting it from Client. Add
an attribute defaultValue and its value.

package com.flipkart.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class OrderController {

//Header is Part of Request, i.e. Should be Come from Client Side.


@GetMapping("/data")
public String testHeaders(@RequestHeader(name = "user-name", required = false,
defaultValue = "flipkart") String userName) {
return "Connected User : " + userName;
}
}

Testing: Without adding Header and its value, triggering Service. Default Value of Header
user-name is flipkart is considered by Server as per implementation.

324 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Setting Response Headers:

In Spring MVC, response headers can be set using the HttpServletResponse object or
the ResponseEntity class.

Here are some of the commonly used response headers in Spring MVC:

Content-Type: The MIME type of the response body.


Expires: The date and time after which the response should no longer be cached.
Last-Modified: The date and time when the resource was last modified.

The HttpServletResponse object is the standard way to set headers in a servlet-based


application. To set a header using the HttpServletResponse object, you can use the
addHeader() method.

For example:

HttpServletResponse response = request.getServletResponse();


response.addHeader("Content-Type", "application/json");

The ResponseEntity class is a more recent addition to Spring MVC. It provides a more concise
way to set headers, as well as other features such as status codes and body content. To set a
header using the ResponseEntity class, you can use the headers() method.

For example:

ResponseEntity<String> response = new ResponseEntity<>("Hello, world!", HttpStatus.OK);


response.headers().add("Content-Type", "application/json");

325 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


In another approach, We can create HttpHeaders instance and we can add multiple Headers
and their values. After that, we can pass HttpHeaders instance to ResponseEntity Object.

HttpHeaders:
In Spring MVC, the HttpHeaders class is provided by the framework as a convenient
way to manage HTTP headers in both request and response contexts. HttpHeaders is part of
the org.springframework.http package, and it provides methods to add, retrieve, and
manipulate HTTP headers. Here's how you can use the HttpHeaders class in Spring MVC:

In a Response:
You can use HttpHeaders to set custom headers in the HTTP response. This is often
done when you want to include specific headers in the response to provide additional
information to the client.

Example: Sending a Header and its value as part of response Body.

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class OrderController {

// Header is Part of Response, i.e. Should be set from Server Side.


@GetMapping("/user/data")
public ResponseEntity<String> testResponseHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.set("token", "shkshdsdshsdjgsjsdg");
return new ResponseEntity<String>("Sending Response with Headers", headers,
HttpStatus.OK);
}
}

Testing: Trigger endpoint from Client: Got Token and its value from Service in Headers.

326 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Exception Handling in Spring MVC Controllers:

What I have to do with Errors or Exceptions ?

Spring brought @ExceptionHandler & @ControllerAdvice annotations for handling


Exceptions thrown at controller layer. So we can handle exceptions and will be forwarded
meaning full Error response messages with response status code to HTTP clients.

If we are not handled exceptions then we will see Exception stack trace as shown in below at
HTTP client level as a response. As a Best Practice we should show meaningful Error Response
messages.

327 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Note: Spring provided other ways as well to handle exceptions but controller advice and
Exception handler will provide better way of exception handling.

@ExceptionHandler is a Spring annotation that provides a mechanism to treat exceptions


thrown during execution of handlers (controller operations). This annotation, if used on
methods of controller classes, will serve as the entry point for handling exceptions thrown
within this controller only.

Altogether, the most common implementation is to use @ExceptionHandler on methods


of @ControllerAdvice classes so that the Spring Boot exception handling will be applied
globally or to a subset of controllers.

ControllerAdvice is an annotation in Spring and, as the name suggests, is “advice” for all
controllers. It enables the application of a single ExceptionHandler to multiple controllers.
With this annotation, we can define how to treat an exception in a single place, and the
system will call this exception handler method for thrown exceptions on classes covered by
this ControllerAdvice.
By using @ExceptionHandler and @ControllerAdvice, we’ll be able to define a central point
for treating exceptions and wrapping them in an Error object with the default Spring Boot
error-handling mechanism.

328 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Solution 1: Controller-Level @ExceptionHandler:

The first solution works at the @Controller level. We will define a method to handle
exceptions and annotate that with @ExceptionHandler i.e. We can define Exception Handler
Methods in side controller classes. This approach has a major drawback: The
@ExceptionHandler annotated method is only active for that particular Controller, not
globally for the entire application. But better practice is writing a separate controller advice
classes dedicatedly handle different exception at one place.

@RestController
public class FooController{

// Endpoint Methods

@ExceptionHandler({ ExceptionName.class, ExceptionName.class })


public void handleException() {
//
}
}
Solution 2: @ControllerAdvice:

The @ControllerAdvice annotation allows us to consolidate multiple Exception Types with


ExceptionHandlers into a single, global error handling component level.

329 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


The actual mechanism is extremely simple but also very flexible:

• It gives us full control over the body of the response as well as the status code.
• It provides mapping of several exceptions to the same method, to be handled together.
• It makes good use of the newer RESTful ResposeEntity response.

One thing to keep in our mind here is to match the exceptions declared
with @ExceptionHandler to the exception used as the argument of the method.

Example of Controller Advice class : Controller Advice With Exception Handler methods

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import jakarta.servlet.http.HttpServletRequest;

@ControllerAdvice
public class OrderControllerExceptionHandler {

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?>
handleMethodArgumentException(MethodArgumentNotValidException ex,
HttpServletRequest rq) {

List<String> messages = ex.getFieldErrors().stream().map(e ->


e.getDefaultMessage()).collect(Collectors.toList());
return new ResponseEntity<>( messages, HttpStatus.BAD_REQUEST);
}

@ExceptionHandler(NullPointerException.class)
public ResponseEntity<?> handleNullpointerException(NullPointerException ex,
HttpServletRequest request) {

return new ResponseEntity<>("Please Check data, getting as null values",


HttpStatus.INTERNAL_SERVER_ERROR);
}

@ExceptionHandler(ArithmeticException.class)
public ResponseEntity<?> handleArithmeticException(ArithmeticException ex,
HttpServletRequest request) {

330 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


return new ResponseEntity<>("Please Exception Details ",
HttpStatus.INTERNAL_SERVER_ERROR);
}

// Below Exception handler method will work for all child exceptions when we are not
//handled those specifically.
@ExceptionHandler(Exception.class)
public ResponseEntity<?> handleException(Exception ex, HttpServletRequest
request) {

return new ResponseEntity<>("Please check Exception Details. ",


HttpStatus.INTERNAL_SERVER_ERROR);
}
}

• Now see How we are getting Error response with meaningful messages when Request
Body validation failed instead of complete Exception stack trace.

How it is working?
Whenever an exception occurred at controller layer due to any reason, immediately
controller will check for relevant exceptions handled as part of Exception Handler or not. If
handled, then that specific exception handler method will be executed and response will be
forwarded to clients. If not handled, then entire exception error stack trace will be forwarded
to client an it’s not suggestable.

Which Exception takes Priority if we defined Child and Parent Exceptions Handlers?

331 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


From above example, if NullPointerException occurred then
handleNullpointerException() method will be executed even though we have logic for parent
Exception handling i.e. Priority given to child exception if we handled and that will be
returned as response data. Similarly we can define multiple controller advice classes with
different types of Exceptions along with relevant Http Response Status Codes.

@RequestMapping consumes and produces attributes:


Spring, by default, configures Jackson for parsing Java objects to JSON and converting
JSON to Java objects as part of REST API request-response handling. When we want to support
other Request and Response Data Formats in REST Services implementation, then we should
define those respective data formats with help of consumes and produces attributes inside
@RequestMapping annotation with endpoint methods. Same attributes and respective
functionalities are applicable to shortcut annotations like @GetMapping, @PostMapping
etc..

consumes:
Using a consumes attribute to narrow the mapping by the content type. You can
declare a shared consumes attribute at the class level i.e. applicable to all controller
methods. Unlike most other request-mapping attributes, however, when used at the class
level, a method-level consumes attribute overrides rather than extends the class-level
declaration.

The consumes attribute also supports negation expressions — for example, !text/plain means
any content type other than text/plain.

MediaType class provides constants for commonly used media/content types, such as
APPLICATION_JSON_VALUE and APPLICATION_XML_VALUE etc..

Now let’s have an example, as below shown. Created an endpoint method, which accepts
only JSON data Request by providing consumes ="application/json".

332 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@RequestMapping(path = "/add/model", consumes ="application/json",
method = RequestMethod.POST)
public String addLaptopDetails(@RequestBody LaptopDetails details) {

return "Addedd Succesfully";


}

LaptopDetails.java : To Bind Request Body of JSON

public class LaptopDetails {


private String lapName;
private double cost;
private int modelYear;

//Setters and Getters


}

Now Trigger Endpoint with JSON data in Request Body.

Now try to trigger same endpoint with XML Request Body.

We will get an exception/error response as shown below.


"error": "Unsupported Media Type",
"trace": "org.springframework.web.HttpMediaTypeNotSupportedException: Content-
Type 'application/xml'

333 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Creating Endpoint which accepts only XML data Request Body:

To support XML request Body, we should follow below configurations/steps. Spring boot, by
default, configures Jackson for parsing Java objects to JSON and converting JSON to Java
objects as part of REST API request-response handling. To accept XML requests and send XML
responses, there are two common approaches.
▪ Using Jackson XML Module
▪ Using JAXB Module
Start with adding Jackson’s XML module by including the jackson-dataformat-xml
dependency. Spring boot manages the library versions, so the following declaration is enough.
Add below both dependencies in POM.xml file of application.

<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>

Now we can define and access REST API Services with XML data format.

➢ Creating a service which accepts only XML Request Body i.e. endpoint accepts now only
XML request body but not JSON.

@RequestMapping(path = "/add/model", method = RequestMethod.POST,


consumes ="application/xml")
public String addLaptopDetails(@RequestBody LaptopDetails details) {
return "Added Successfully";
}

334 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Now Trigger Endpoint with XML Request data in Body.

Create endpoint which supports both JSON and XML Request Body.

Below URI Request Mapping will support both XML and JSON Requests. We can pass multiple
data types consumes attribute with array of values.

@RequestMapping(path = "/add/model", method = RequestMethod.POST,


consumes ={"application/json","application/xml"})
public String addLaptopDetails(@RequestBody LaptopDetails details) {

return "Addedd Succesfully";


}

Spring Provided a class MediaType with Constant values of different Medi Types. We will use
MediaType in consumes and produces attributes values.

consumes ={"application/json","application/xml"}
is equals to
consumes ={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}

335 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


produces: with produces attributes, we can configure which type of Response data should
be generated from Response object.

Endpoint Producing Only XML response:


Configure Request mapping with produces = MediaType.APPLICATION_XML_VALUE. So that now
it will generate only XML response.

@RequestMapping(path = "/model/2345", method = RequestMethod.GET,


produces = MediaType.APPLICATION_XML_VALUE)
public LaptopDetails getLaptopDetails() {
LaptopDetails lap = new LaptopDetails();
lap.setCost(80000.00);
lap.setLapName("Thinkpad");
lap.setModelYear(2023);
return lap;
}

Above endpoint generates only XML response for every incoming request.

Creating an Endpoint Producing both JSON and XML response.


Configure Request mapping with produces attribute supporting both Media Types
values i.e. array of values. So that now this endpoint generates either XML or JSON response
depends on header Accept and its value. The HTTP Accept header is a request type header.
The Accept header is used to inform the server by the client that which content type is
understandable by the client.

336 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


@RequestMapping(path = "/model/2345", method = RequestMethod.GET, produces = {
MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public LaptopDetails getLaptopDetails() {
LaptopDetails lap = new LaptopDetails();
lap.setCost(80000.00);
lap.setLapName("Thinkpad");
lap.setModelYear(2023);
return lap;
}

Request for XML response: Add Header Accept and value as application/xml as shown.

Request for JSON response: Add Header Accept and value as application/json as shown.

337 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Producing and Consuming REST API services:

Producing REST Services:


Producing REST services is nothing but creating Controller endpoint methods i.e.
Defining REST Services on our own logic. As of Now we are created/produced multiple REST
API Services with different examples by writing controller layer and URI mapping methods.

Consuming REST Services:

Consuming REST services is nothing but integrating/calling other application REST API
services from our application logic.

For Example,
ICICI bank will produce API services to enable banking functionalities. Now Amazon
application integrated with ICICI REST services for performing Payment Options.

In This case:
Producer is : ICICI
Consumer is : Amazon

In Spring MVC, Spring Provided an HTTP or REST client class called as RestTemplate from
package org.springframework.web.client. RestTemplate class provided multiple utility
methods to consume REST API services from one application to another application.

338 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


RestTemplate is used to create applications that consume RESTful Web Services. You can use
the exchange() or specific http methods to consume the web services for all HTTP methods.
Now we are trying to call Pharmacy Application API from our Spring Boot Application Flipkart
i.e. Flipkart consuming Pharmacy Application REST API.
Now I am giving only API details of Pharmacy Application as swagger documentation. Because
in Realtime Projects, swagger documentation or Postman collection data will be shared to
Developers team, but not source code. So we will try to consume by seeing Swagger API
documentation of tother application. When you are practicing also include swagger
documentation to other application and try to implement by seeing swagger document only.
NOTE: Please makes sure other application running always to consume REST services.
Below snap shows what are all services available in side pharmacy application.

339 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Consuming REST Services with Request Body:
Requirement : Now I want to call Rest service /add/store/location of pharmacy application
from my Flipkart application.

Go to swagger and expand details of /add/store/location in swagger documentation.

From above swagger snap, we should understand below points for that API call.
1. URL : http://localhost:6677/pharmacy/add/store/location
2. HTPP method: POST
3. Request Body Should contain below payload structure

340 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


{
"locationName": "hyderabad",
"conatcNumber": "323332323",
"pincode": 500099
}

4. Response Receiving as String Format.

Same we can see in Postman as shown below.

Now based on above data, we are going to write logic of RestTemplate to consume in our
application flipkart.

Now assume we are receiving data from UI/Frontend to Flipkart application and that data we
are transferring to Pharmacy API with help of RestTemplate.

NOTE : All code changes will happen only in flipkart application.

@RestController
@RequestMapping("/pharmacy")
public class PharmacyController {

@Autowired
PharmacyService pharmacyService;

@PostMapping("/add/location")
public String addPharmacyDetails(@RequestBody PharmacyLocation request) {
return pharmacyService.addPharmacyDetails(request);
}
}

➢ Now in Service class, we should write logic of integrating Pharmacy endpoint for adding
store details as per swagger notes.

341 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ Crate a POJO class which is equal to JOSN Request payload of Pharmacy API call.

PharmacyData.java : This Object will be used as Request Body

public class PharmacyData {

private String locationName;


private String conatcNumber;
private int pincode;

//setters and getters


}

HttpEntity:
HttpEntity class is used to represent an HTTP request or response entity. It
encapsulates/binds the HTTP message's headers and body. You can use HttpEntity to
customize the headers and body of the HTTP request before sending it using RestTemplate. It
provides more control and flexibility over the request or response compared to simpler
methods like getForEntity(), postForObject(), etc.

Here's how you can use HttpEntity in RestTemplate:

➢ Now In service layer, Please map data from controller layer to API request body class.

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.flipkart.dto.PharmacyData;
import com.flipkart.pharmacy.request.PharmacyLocation;

@Service
public class PharmacyService {

public String addPharmacyDetails(PharmacyLocation location) {

//complete URL of pharmacy endpoint.


String url = "http://localhost:6677/pharmacy/add/store/location";

342 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


//Mapping from flipkart request object to JSON payload Object of class i.e.
PharmacyData
// Java Object which should be aligned to Pharmacy POST end point Request body.
PharmacyData data = new PharmacyData();
data.setConatcNumber(location.getContact());
data.setLocationName(location.getLocation());
data.setPincode(location.getPincode());

// converting our java object to HttpEntity : i.e. Request Body


HttpEntity<PharmacyData> body = new HttpEntity<PharmacyData>(data);
RestTemplate restTemplate = new RestTemplate();
return restTemplate.exchange(url, HttpMethod.POST, body, String.class).getBody();
}
}

➢ Now Test it from Postman and check pharmacy API call triggered or not i.e. check data is
inserted in DB or not from pharmacy application.

flipkart URL : localhost:9966/flipkart/pharmacy/add/location

➢ Now create Request body as per our controller request body class.

{
"location": "pune",
"contact": "+918125262702",
"pincode": 500088
}

➢ Before executing from post man, please check DB data. In my table I have below data right
now.

343 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


➢ Now from postman send request as per flipkart controller method.

➢ Request executed successfully and you got response from Pharmacy API of post REST API
call what we integrated. Verify In Database record inserted or not. It’s inserted.

344 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Internal Execution/Workflow:

When we are sending data to flipkart app, now flipkart app forwarded data to pharmacy
application via REST API call.

Now Let’s integrate Path variable and Query Parameters REST API Services:
Consuming API Services with Query Parameters:

Example1 : Consume below Service which contains Query String i.e. Query Parameters.

345 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


Consuming GET API Service with Query Parameter:

In RestTemplate, to handle Query Parameters Spring provided flexibility with


Hashmap Object i.e. Configuring Query parameters with values key and values. Above Service
Producing Response as JSON array of Objects. So create Response Class.

PharmacyResponse.java:

public class PharmacyResponse {

private String locationName;


private String conatcNumber;
private int pincode;

//Setters and Getters


}

➢ From above API details, we have one Request Parameter : locationName.

public List<PharmacyResponse> loadDetailsByLocationName(String location) {

String url = "http://localhost:6677/pharmacy/location?locationName={locationName}";

346 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


// For Query parameters
Map<String, String> values = new HashMap<>();
values.put("locationName", location); // passing value with location

RestTemplate restTemplate = new RestTemplate();


List<PharmacyResponse> respone = restTemplate.exchange(url, HttpMethod.GET,
null, List.class, values).getBody();
return respone;
}

Consuming Another Example with Query Parameters:

➢ Consume Below REST Service which contains Query Parameters From our Application.

Source of REST Service to be consumed:

➢ Logic for Consumption:

package com.flipkart.service;

import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

public class RestTemplateExample {

347 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


public static void main(String[] args) {

// Create a RestTemplate instance


RestTemplate restTemplate = new RestTemplate();

// Define the base URL of the API


String baseUrl = "http://localhost:8899/icici/api/test";

// Create query parameters using UriComponentsBuilder


UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl)
.queryParam("accountNumber", "122334455")
.queryParam("loanType", "House");

// Build the final URL with query parameters


String finalUrl = builder.toUriString();

// Make a GET request to the API


ResponseEntity<String> response = restTemplate.getForEntity(finalUrl, String.class);

// Process the response


if (response.getStatusCode().is2xxSuccessful()) {
String responseBody = response.getBody();
System.out.println(responseBody);
} else {
System.err.println("Request failed with status code: " + response.getStatusCode());
}
}
}

Output:

{
"userName":"Suresh Singh",
"accountBalance":4040000.0,
"accountNumber":"122"
}

Consuming GET API Service with Path Parameter:


Example : Consume below Service which contains Path Variable.
In RestTemplate, to handle Path Parameters Spring provided flexibility with Hashmap
Object or Object Type Variable Arguments as part of exchange() i.e. Configuring Path
parameters with values. Above Service Producing Response as JSON array of Objects. So
create Response Class.

348 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


PharmacyResponse.java

public class PharmacyResponse {

private String locationName;


private String conatcNumber;
private int pincode;

//Setters and Getters


}

➢ From above API details, we have one Path Parameter : locationName.

public List<PharmacyResponse> loadByLocationName(String location) {

String url = "http://localhost:6677/pharmacy/location/{locationName}";

Map<String, String> values = new HashMap<>();


values.put("locationName", location);

RestTemplate restTemplate = new RestTemplate();


List<PharmacyResponse> respone = restTemplate.exchange(url, HttpMethod.GET,
null, List.class, values).getBody();

return respone;
}

349 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


NOTE: We can handle both Path variable and Query Parameters of a single URI with Hashmap
Object. i.e. We are passing values to keys. Internally spring will replace values specifically.

Integration of One More REST API Service:

➢ Example 3: We are Integrating one Real time API service from Online.

REST API GET URL: https://countriesnow.space/api/v0.1/countries/positions

Above API call, Producing JSON Response, as shown in below Postman. Depends on Response
we should create JAVA POJO classes to serialize data from JAVA to JSON and vice versa.

➢ Based on API call Response, we should create Response POJO classes aligned to JSON
Payload.

Country.java
public class Country {
private String name;
private String iso2;
private int lat;

//Setters and Getters


}
CountriesResponse.java

public class CountriesResponse {

350 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


private boolean error;
private String msg;
private List<Country> data;

//Setters and Getters


}

API Consuming Logic:

public CountriesResponse loadCities() {

String url = "https://countriesnow.space/api/v0.1/countries/positions";

RestTemplate restTemplate = new RestTemplate();


CountriesResponse respone = restTemplate.exchange(url, HttpMethod.GET,
null, CountriesResponse.class).getBody();

System.out.println(respone);
return respone;
}

➢ Testing from our Application Postman:

351 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


How to Pass Headers with RestTemplate when Consuming REST Services:

In Spring's RestTemplate, we can work with HTTP headers by using the HttpHeaders
class. You can add, retrieve, and manipulate headers in both requests and responses. Here's
how we can work with headers in RestTemplate:

Adding Headers to a Request:

In this example, we create an HttpHeaders object and set custom headers. We can add
headers to your HTTP request before sending it using RestTemplate. Here's an example of how
to add headers to a request:

import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

352 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


public class RestTemplateHeadersExample {
public static void main(String[] args) {

// Create a RestTemplate instance


RestTemplate restTemplate = new RestTemplate();

// Define the request URL


String url = "https://api.example.com/api/resource";

// Create an HttpHeaders object to set custom headers


HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer yourAccessToken");
headers.set("Custom-Header", "Custom-Value");
headers.add("token", "dss3232444gt54t5tgrgtry54y5ydsdsdsdsdsdsd");

HttpEntity<Object> entity = new HttpEntity<Object>(headers);

// Create a HttpEntity with the custom headers


ResponseEntity<String> responseEntity =
restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

// Process the response


if (responseEntity.getStatusCode().is2xxSuccessful()) {
String responseBody = responseEntity.getBody();
System.out.println("Response: " + responseBody);
} else {
System.err.println("Request failed with status code: " +
responseEntity.getStatusCode());
}
}
}
Accessing Headers in a Response:

We can access response headers when you receive a response from the server. Here's
an example:

import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class RestTemplateResponseHeadersExample {

public static void main(String[] args) {


// Create a RestTemplate instance
RestTemplate restTemplate = new RestTemplate();

// Define the request URL


String url = "https://api.example.com/api/resource";

353 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)


// Send a GET request and receive the entire ResponseEntity for the response
ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);

// Access response headers


HttpHeaders responseHeaders = responseEntity.getHeaders();
String contentType = responseHeaders.getFirst("Content-Type");
long contentLength = responseHeaders.getContentLength();

System.out.println("Content-Type: " + contentType);


System.out.println("Content-Length: " + contentLength);

// Access the response body


String responseBody = responseEntity.getBody();
System.out.println("Response Body: " + responseBody);
}
}

In this example, we use responseEntity.getHeaders() to access the response headers and then
retrieve specific header values using responseHeaders.getFirst("Header-Name").

Working with headers allows you to customize your requests and process responses more
effectively in your RestTemplate interactions.

354 Spring & SpringBoot Dilip Singh (dilipsingh1306@gmail.com)

You might also like