0% found this document useful (0 votes)
2 views138 pages

Module 2

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views138 pages

Module 2

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

MODULE 2:

SpringBoot: WhatisSpringBoot-CreatingaProjectwithSpringBootInitializer,
Wirebeans together in the Spring container using Inversion of Control,
Configure the Spring container for Dependency Injection, Define Spring
Beans using the Component annotation, perform auto- scanning of Spring
beans to minimize configuration, Automatically wire beans together using
Auto wired annotation, Apply all Java configuration to Spring Beans (no
xml).

Spring Boot Rest API: Writing RESTful controllers, Consuming REST


services; Spring Boot RESTAPIValidation:ValidationwithSpringBoot–
Overview,ValidateCreatePostandUpdate Post REST API Request, Customizing
Validation Response, Validate Create Comment and Update Comment REST
API

What is Spring Boot?

Spring Boot is a Java-based framework built on top of the Spring Framework. It


simplifies Java development by providing pre-configured settings, auto-configuration,
and embedded web servers like Tomcat. Spring Boot helps developers build
production-ready, scalable, and secure applications quickly, particularly in the context
of web applications and enterprise solutions.

Key Use Cases of Spring Boot

1. Building Web Applications

One of the primary uses of Spring Boot is to create web applications. It makes it easy
to build both traditional web apps and RESTful APIs. With Spring Boot, you can
create web applications quickly by leveraging features like:

• Spring MVC for building web-based applications and handling HTTP


requests.
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

• Thymeleaf and other template engines for rendering dynamic web pages.(html)
• Embedded Tomcat server, which allows you to run your web application
without needing to configure an external web server.

import [Link];
import [Link];
import [Link];
import [Link];
@SpringBootApplication
publicclassMyWebApp{ publicstaticvoidmain(String[] args) {
[Link]([Link], args);
}
}
@RestController
classHelloController{ @GetMapping("/hello")
public String sayHello()
{ return"Hello, Spring Boot!";
}
}

Creating REST APIs

Spring Boot is widely used to build RESTful web services. REST APIs are a
common way to allow different systems or clients (such as web browsers or mobile
apps) to interact with your backend services. Spring Boot simplifies the process of
creating these APIs with minimal boilerplate code.

Example:
import [Link].*;
@RestController
@RequestMapping("/api")
publicclassApiController
{
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

@GetMapping("/greeting")
public String getGreeting()
{
return"Hello, this is a REST API!";
}
}

Microservices Development

Spring Boot is one of the top choices for building microservices. A microservice is a
small, independent service that performs a specific function and communicates with
other services to build larger systems. Spring Boot’s lightweight, modular design
makes it easy to create, deploy, and scale microservices.

Spring Boot works seamlessly with Spring Cloud, which adds tools for managing
microservices, such as:

• Service discovery (Eureka)


• Load balancing (Ribbon)
• API Gateway (Zuul)
• Distributed tracing (Sleuth)

Database Access and Management

Another common use of Spring Boot is to manage databases and data storage. Spring
Boot supports various databases, including MySQL, PostgreSQL, MongoDB,
and H2. It integrates seamlessly with Spring Data JPA, which simplifies database
access and management by using an Object-Relational Mapping (ORM) approach.

import [Link];
publicinterfaceUserRepositoryextendsJpaRepository<User, Long>
{
User findByUsername(String username);
}
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

Building Enterprise-Grade Applications

Many companies use Spring Boot to develop large, enterprise-level applications.


Spring Boot provides a solid foundation for building secure, scalable, and reliable
systems. Its production-ready features include:

• Spring Security for handling authentication and authorization.


• Spring Boot Actuator for monitoring and managing applications in
production environments.
• Logging and metrics to track application performance and troubleshoot issues.

Spring Boot’s modular approach allows developers to add features as needed without
overwhelming the system. This makes it perfect for building both small and large
applications.

Running Standalone Applications

Spring Boot is often used to build standalone applications. You can package your
Spring Boot application as a JAR file and run it without needing an external web
server. This is particularly useful for creating small tools, utilities, or background
services.

With the built-in Spring Boot CLI (Command Line Interface), you can even write
and run Spring Boot applications directly from the command line, making it easy to
develop and test quick solutions.

Cloud-Based Application Development

Spring Boot is an excellent choice for building cloud-native applications. It integrates


well with cloud platforms like AWS, Google Cloud, and Microsoft Azure. Spring
Boot’s ease of use and flexibility make it simple to build applications that can be
deployed to the cloud.

Using tools like Spring Cloud, you can build cloud-ready, scalable, and resilient
applications. Spring Cloud helps manage distributed systems, providing features like
centralized configuration, load balancing, and service discovery.
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

Rapid Prototyping

Spring Boot is often used for rapid prototyping because of how quickly you can
create and deploy an application. With Spring Boot’s Spring Initializr, you can
generate a project within minutes, add dependencies, and start building your prototype.
This makes it perfect for developers who need to build proof-of-concept applications
quickly.

Key Reasons Spring Boot is Opinionated:

Auto-Configuration

One of the biggest reasons Spring Boot is called opinionated is its auto-
configuration feature. When you create a Spring Boot project and add certain
dependencies (such as a database or web framework), Spring Boot
automatically configures them for you.

For example:

1. If you add a database dependency like H2 or MySQL, Spring Boot


will automatically configure the database connection.
2. If you include Spring Web, Spring Boot sets up an embedded server
(like Tomcat) and configures it to handle HTTP requests.

You don’t need to write configuration files or deal with manual setup—Spring
Boot makes an assumption about what you need and configures it accordingly.

Starter Dependencies

Spring Boot provides starter dependencies, which are pre-packaged sets of


libraries and tools that are commonly used together. This makes it easier to get
started with a project. For example, if you want to build a web application,
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

you can simply include the spring-boot-starter-web dependency, and it will


automatically include everything you need, such as:

1. Spring MVC for web functionality


2. Tomcat for the embedded server
3. Jackson for JSON parsing
4. Logging libraries

The opinionated nature of Spring Boot means it assumes which dependencies


you’ll need and sets them up for you. This reduces the burden of manually
choosing and configuring individual libraries.

Embedded Web Servers

In traditional Spring applications, you’d need to set up and configure an


external web server like Tomcat or Jetty. Spring Boot simplifies this
by including embedded web servers as part of the project setup. You don’t
need to install or configure a separate server—Spring Boot makes the decision
for you and includes the most commonly used web server, Tomcat, by default.

This "opinion" helps developers get their applications running quickly,


without worrying about setting up and configuring web servers.

Production-Ready Features

Spring Boot includes a variety of production-ready features such as health


checks, metrics, and monitoring tools out of the box. This is part of Spring
Boot’s opinionated approach: it assumes you’ll need these features when
deploying your application and sets them up for you.

For example:

1. The Spring Boot Actuator module automatically configures endpoints


for checking application health, viewing metrics, and gathering
information about the app’s environment.
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

2. Logging is pre-configured with sensible defaults, so you don’t have to


manually set up loggers.

These production-ready features show Spring Boot’s opinionated nature by


assuming what tools you’ll need for production and automatically integrating
them into your project.

Convention Over Configuration

Spring Boot follows the principle of “convention over configuration”. This


means that instead of requiring developers to explicitly configure everything,
it provides reasonable defaults that follow best practices. For example:

1. By default, Spring Boot will look for


an [Link] or [Link] file to configure settings.
2. If you don’t define certain settings (like port numbers), Spring Boot
will assume default values.

This makes development faster because you don’t need to spend time
configuring things that have widely accepted standards or defaults. However,
if you need to customize these settings, Spring Boot allows youto override
them.

1. Three Tier (Three Layer) Architecture

Three-tier (or three-layer) architecture is a widely accepted solution to organize the


codebase. According to this architecture, the codebase is divided into three separate
layers with distinctive responsibilities:
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

Presentation layer: This is the user interface of the application that presents the
application’s features and data to the user.

Presentation layer: This is the user interface of the application that presents the
application’s features and data to the user.

Business logic (or Application) layer: This layer contains the business logic that
drives the application’s core functionalities. Like making decisions, calculations,
evaluations, and processing the data passing between the other two layers.

Data access layer (or Data) layer: This layer is responsible for interacting with
databases to save and restore application data.

2. Three Tier (Three Layer) Architecture VS MVC Pattern

Let's see how these two architectural patterns (both containing three connected
components) relate to each other.

The MVC pattern is only concerned with organizing the logic in the user interface
(presentation layer).
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

As the name implies, the MVC pattern has three layers: The Model defines the
business layer of the application, the Controller manages the flow of the application,
and the View defines the presentation layer of the application.

The Model Layer - This is the data layer which contains the business logic of
the system, and also represents the state of the application. It’s independent of
the presentation layer, the controller fetches the data from the Model layer and
sends it to the View layer.

The Controller Layer - The controller layer acts as an interface


between View and Model. It receives requests from the View layer and
processes them, including the necessary validations.

The View Layer - This layer represents the output of the application, usually
some form of UI. The presentation layer is used to display the Model data
fetched by the Controller.

Three-tier architecture has a broader concern. It’s about organizing the code in the
whole application.

The controller component of MVC is the connection point between the two layers:
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

How to use Three-layer architecture in Spring MVC web applications.

In a Spring MVC web application, the three layers of the architecture will manifest as
follows:

• Controller classes as the presentation layer. Keep this layer as thin as possible
and limited to the mechanics of the MVC operations, e.g., receiving and
validating the inputs, manipulating the model object, returning the
appropriate ModelAndView object, and so on. All the business-related
operations should be done in the service classes. Controller classes are usually
put in a controller package.

• Service classes as the business logic layer. Calculations, data transformations,


data processes, and cross-record validations (business rules) are usually done
at this layer. They get called by the controller classes and might call
repositories or other services. Service classes are usually put in a service
package.

• Repository classes as data access layer. This layer’s responsibility is limited


to Create, Retrieve, Update, and Delete (CRUD) operations on a data source,
which is usually a relational or non-relational database. Repository classes are
usually put in a repository package.
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

Consider below Spring MVC web application using Spring boot and thymeleaf. We
have created a three-layer architecture and each layer is mapped to the corresponding
package.
For example:

• Presentation Layer - controller package


• Business Logic Layer - service package
• Data Access Layer - repository package
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

Dependency Injection at a Glance

Dependency Injection is a straightforward concept that becomes incredibly powerful


when used correctly. Essentially, if you manually instantiate an object, you have a
few approaches:

Use the default constructor and instantiate properties via setters.

Use a non-default constructor and pass all parameters into it.

Use the default constructor and reflection to instantiate private class fields.

Spring simplifies this process by searching for dependencies by type, making it


easier to wire dependencies into your classes.

To handle this automatic wiring, Spring uses the @Autowired annotation, which
marks the points where dependencies should be injected. You can place
@Autowired on constructors, methods, and properties to indicate where Spring
should inject dependencies.

[Link] Dependency Injection

Setter-based DI involves creating an object using the default constructor and then
setting its dependencies through setter methods.

Example:

package [Link];

import [Link];

import [Link];

@Component
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

public class Sandwich {

private Bread bread;

private Cheese cheese;

public Sandwich() {

// Default constructor

@Autowired

public void setBread(Bread bread) {

[Link] = bread;

@Autowired

public void setCheese(Cheese cheese) {

[Link] = cheese;

In this example, @Autowired on the setBread and setCheese methods indicates


that Spring should automatically call these setter methods to pass the appropriate
Bread and Cheese dependencies. Spring first uses the default constructor to create
an instance of Sandwich, then calls these methods to inject the dependencies.
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

[Link] Dependency Injection

Constructor-based DI involves passing all dependencies into the constructor to


create an object.

Example:

package [Link];

import [Link];

import [Link];

@Component

public class Salad {

private Lettuce lettuce;

private Tomato tomato;

// @Autowired is optional here

public Salad(Lettuce lettuce, Tomato tomato) {

[Link] = lettuce;

[Link] = tomato;

In this example, although @Autowired is used on the constructor (it is optional


when there is only one constructor), it indicates that Spring should use this
constructor and provide the necessary Lettuce and Tomato dependencies. Spring
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

finds all the required dependencies in the application context and uses them in the
Salad constructor to instantiate the object.

[Link] Dependency Injection

Field-based DI involves directly injecting dependencies into class fields, even if


they are private.

Example:

package [Link];

import [Link];

import [Link];

@Component

public class Juice {

@Autowired

private Water water;

@Autowired

private Sugar sugar;

// Getters for water and sugar can be added if needed

In this example, @Autowired is placed directly on the fields water and sugar. Spring
uses reflection to inject dependencies into these private fields. While convenient,
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

this method is generally discouraged due to its reduced testability and encapsulation
issues.

Method Dependency Injection with `@Bean`

Spring also allows for method-based dependency injection using the @Bean
annotation. This technique involves injecting dependencies via method parameters
in Java configuration classes.

Example:

package [Link];

import [Link];

import [Link];

@Configuration

public class AppConfig {

@Bean

public Sandwich sandwich(Bread bread, Cheese cheese) {

return new Sandwich(bread, cheese);

@Bean

public Bread bread() {

return new Bread();

}
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

@Bean

public Cheese cheese() {

return new Cheese();

In this example, the sandwich method is annotated with @Bean, and it takes Bread
and Cheese as parameters. Spring's application context will automatically resolve
these dependencies by calling the bread and cheese methods, respectively, to supply
the required beans. This method-based injection is useful for creating bean instances
that depend on other beans defined in the same configuration class.

What is a Spring Bean?

• The Spring framework defines a Spring bean as an object managed by the


Spring Inversion of Control (IoC) container.

The Spring IoC container’s management of beans includes several responsibilities.


Perhaps the most significant of which include bean instantiation/assembly and the
management of dependency injections. Let’s take a look at each of these key features
to gain a greater understanding of beans and how the Spring framework abstracts the
complexity away with simple, easy-to-use annotations

Bean-stantiation

For this article, we assume an understanding that classes are templates from which
objects are created. The process of creating an instance from a class is known as
instantiation. In terms of reusability, we should also have the understanding that
custom objects can be nested inside of other classes.
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

Normally, instantiating an object from a class requires the use of the new keyword.
Let’s take a look at how we would normally use nested objects and compare it to a
similar process when using Spring beans.

Imagine we are designing a racing game. For each round of the race we need a race
track and drivers. We could create a class for both as shown below.

publicclassRaceTrack{
privateString location;
privateint miles;
privateString trackType;
}

publicclassDriver{
privateString name;
privateString team;
privateint yearsExperience;
}

Now let’s create a class that can be used for each round of the race.

publicclassRaceRound{
privateStringstartTime;
privateRaceTrack=newRaceTrack();
privateDriver=newDriver();
}
For each round of the race we would need to instantiate a RaceTrack and a Driver, so
we would use the new keyword to handle those instantiations. Any changes to those
two classes would require additional changes in the RaceRound class.

Now let’s take a look at how instantiating the nested objects would work with Spring
beans. We would first mark our RaceTrack and Driver classes as Spring beans using
the @Component annotation:
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

@Component
publicclassRaceTrack{
privateString location;
privateint miles;
privateString trackType;
}

@Component
publicclassDriver{
privateString name;
privateString team;
privateint yearsExperience;
}
Then we remove the actual instantiation code from RaceRound, instead using
the @Autowired annotation:

publicclassRaceRound{
privateString startTime;
@Autowired
privateRaceTrack currentRaceTrack;
@Autowired
privateDriver currentDriver;
}

Notice we are no longer using the new keyword when creating instances
of RaceTrack and Driver. So, how are we able to declare and use an instance without
instantiating it?

We marked our dependent classes RaceTrack and Driver as Spring beans, which
allows the IoC container to manage them, i.e. instantiate them and inject them into
our RaceRound class.

As an additional bonus, we didn’t have to edit the existing code in


our RaceTrack and Driver classes to turn them into Spring beans. All we had to add
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

was the @Component annotation. There is an additional, older way to do this with
XML configuration, but we’ll focus on the more modern annotations approach.

Auto-beans loading…

The fully-automatic annotations approach is facilitated using three annotations:

• @Configuration, which notifies the framework that beans may be created via
the annotated class.
• @ComponentScan, which tells the framework to scan our code for
components such as classes, controllers, services, etc.
• @EnableAutoConfiguration, which tells the container to auto-create beans
from the found components.

Using three separate annotations may seem hard to recall. However, remember when
we said “the Spring framework abstracts the complexity away with simple, easy-to-
use annotations”? This remains true as these three significant annotations have been
wrapped up into one.

The @SpringBootApplication annotation is a compilation of @Configuration,


@ComponentScan, and @EnableAutoConfiguration. When we apply the
@SpringBootApplication annotation to the class containing our main method, our
application runs with all of this built-in functionality. Therefore, when our application
starts up the container scans our code for components from which beans should be
instantiated.

You can find this annotation provided in most default Spring projects:

@SpringBootApplication

public class RecipeApplication {

public static void main(String[] args) {

[Link]([Link], args);

}
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

Now let’s take a look at what happens during the bean creation process.

Cooking with Beans

We are familiar with the notion of classes containing properties and methods. The
Spring framework represents beans as a BeanDefinition object. The BeanDefinition
object has several properties, but two are particularly interesting. There is a property
named class and there is a property named properties.

When we define classes, we give them a particular name, such as RaceRound. When
the container instantiates a bean from this class it populates the class property of that
bean with the fully qualified name we have provided. So, if the fully qualified name
of our class is [Link], the class property of the bean
becomes [Link]. The class property is Spring’s
way of representing the bean’s underlying Java type so it knows what to instantiate.

The properties property of the bean is populated from the properties of our class. If we
have used a built-in type such as an int or a string, the container converts the property
of our class into the same type of property for the bean. However, if we have used a
custom type, such as RaceTrack or Driver, this is a dependency and the container now
has to create a BeanDefinition object for each of these types as well. Ultimately, the
classes we create become part of a recipe for the container to use when creating beans.

When a class encapsulates other objects, the referenced objects become a dependency
for the outer class. In other words, these other objects must be created so the outer
class can use it. The container takes a look at our classes and, depending on the
method you choose, instantiates beans from the referenced objects (RaceTrack and
Driver) before it instantiates a bean from the outer classes (RaceRound). Spring
implements a way for the objects needed by another object to be provided as beans for
others to reference. This process is known as dependency injection; Our classes no
longer have to instantiate their own dependencies. Therefore, we can say the control
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

of dependencies has been inverted back to the container, and this is why we call it an
Inversion of Control (IoC) container.

Bean there, done that

In our previous examples, we declared our dependencies in RaceRound with fields


and annotated them with @Autowired. In other Spring applications, you’ll often see
dependencies injected via the constructor (which doesn’t require an annotation). In
this example, the dependency is CoffeeRepository:

public class CoffeeController {

private final CoffeeRepository coffeeRepository;

public CoffeeController(CoffeeRepository coffeeRepo) {

[Link] = coffeeRepo;

What is Spring Container?

Spring Container is the "Core Part" or say "Heart " of the Spring Framework which is
responsible for creation, configuration and managing the lifecycle of beans (objects)
It follows the IoC (Inversion of Control) principle by injecting dependencies
automatically, reducing tight coupling between components.
It reads configuration metadata (XML, annotations, or Java config) to know how to
manage the beans.

Responsibilities of Spring Container

Below are some key responsibilities of the Spring Container :-


1. Bean Creation and Initialization :

• Spring Container is responsible to create and initialize the beans (objects)


defined in the Spring configuration.

2. Bean Configuration Handling :


CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

• Spring Container is responsible to loads the configuration from XML,


annotations or Java-based configuration files.

3. Bean Lifecycle Management :

• Spring Container is responsible to handle the complete bean lifecycle,


including initialization (@PostConstruct) and destruction (@PreDestroy).

4. Beans Scope Management :

• Spring Container supports different bean scopes (e.g., singleton, prototype) to


control the lifecycle and usage of beans.

5. Dependency Injection (DI) :

• Spring Container injects the dependencies between objects, ensuring loose


coupling.

6. AOP (Aspect-Oriented Programming) Support :

• Spring Container allows cross-cutting concerns like logging and security to be


modularized through aspects.

7. Integration with Other Technologies :

• Spring Container supports integration with databases, messaging services and


web frameworks.

8. Internationalization (I18N) Support :

• Spring Container supports Internationalization (i18n), enabling applications to


present messages, formats, and resources in multiple languages, making it
adaptable for users across different regions.

9. Environment Management :

• Spring Container provides support for property sources and profiles for
environment-specific configurations.

10. Bean Post-Processing :

• Spring Container allows the use of BeanPostProcessor to modify bean


instances before and after initialization.

Working of Spring Container


CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

1. Java Classes : Java classes (like POJO's & JavaBean's) are used to create
simple Java objects that represent components or beans in the application.
They contain business logic, but are independent of the Spring framework.
2. Configuration Metadata : Configuration files (like XML files, Java-based
configuration classes or annotations) provide the metadata which specifies:
1. Which classes to instantiate as beans.
2. How beans are wired together (dependency injection)
3. The lifecycle and scope of each bean.
3. Spring Container :

1. The Spring Container reads the configuration metadata and scans the
specified classes.
2. It then instantiates and configures the required beans, applying
dependency injection as specified.
3. The container manages the lifecycle of these beans, creating them as
needed and handling initialization, dependencies, and destruction.

4. Bean Objects : The container creates and stores instances of beans based on
the configuration. These are the fully managed objects that can be injected or
retrieved throughout the application.
5. Accessing Beans : Once created, these bean objects are accessible throughout
the application. They can be injected into other components or accessed on
demand using dependency injection or by looking up beans from the container.
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

Types of Spring Container

There are 2 types of Spring Container :-

1. BeanFactory

2. ApplicationContext

"BeanFactory" Container:

BeanFactory Container is lightweight and basic IoC container.

BeanFactory Container creates the beans when they are requested and this concept is
known as Lazy Initialization.

BeanFactory Container is suitable for simple applications where performance is


crucial and resources are limited.

"ApplicationContext" Container

ApplicationContext Container is more advanced version of BeanFactory with extra


features like AOP & Internationalization (I18N) support, event propagation,
declarative mechanisms etc

ApplicationContext Container creates the beans during container startup and this
concept is known as Eager Initialization.

ApplicationContext Container is suitable for Enterprise-level applications that require


more features, such as transactions, events, and AOP.

What is Spring Configurations?

• In Spring; configurations refers to the "instructions" and "setup" that are


provided to the Spring Container.
• Some basic spring configurations are :-
o What beans should be created (eg. service classes, repositories)
o How beans should be wired or connected (dependency injection)
o Scope of beans (eg. singleton, prototype)
o Life cycle methods (initialization and destruction methods)
o (and many more configurations which are explained below)
• According to the provided configurations, Spring Container performs the
particular task.

Important Configurations in Spring :

Below are some commonly used configurations in spring :-


CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

1. Bean Configurations : Bean Configurations defines the beans (objects) that


Spring will manage, including their properties, dependencies and lifecycle
methods. It specify how beans are instantiated and injected into each other.
2. Autowiring Configurations : Autowiring Configurations manages
dependency injection automatically by wiring beans based on type, name, or
explicitly with annotations like @Autowired, @Qualifier, or @Inject.
3. AOP Configurations : AOP Configurations configures aspects and advice for
handling cross-cutting concerns such as logging, transactions, and security.
This can include defining aspects, pointcuts, and advice types.
4. Database Configurations : Database Configurations configures the data
sources, connection pools and Hibernate/JPA settings for interacting with
databases. This often includes setting up properties like database URL,
username, password, and Hibernate dialect.
5. Transaction Management Configurations : Transaction Management
Configurations configures transactional behavior for methods interacting with
databases, using @Transactional annotations or XML configurations.
Specifies when transactions begin, commit, or roll back.
6. MVC Configurations : MVC Configurations configures settings related to
the Spring MVC framework, including view resolvers, handler mappings,
interceptors, and static resource handling.
7. Security Configurations : Security Configurations Configures application
security settings, including authentication, authorization, and access control.
Security configurations may specify user roles, authentication providers, and
access restrictions.
8. Profile Configurations : Profile Configurations allows configurations based
on different environments (e.g. development, testing, production). By setting
profiles, Spring loads specific beans or properties depending on the active
environment.
9. Caching Configurations : Caching Configurations enables caching in the
application using @EnableCaching. This allows caching results of methods
or components to improve performance.
10. Scheduling Configurations : Configures tasks to run at scheduled intervals
using @EnableScheduling and @Scheduled annotations.
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

These are only some common configurations that we provide in spring applications.
As you keep reading further and creating more programs, you will understand these
configurations more deeply...!!

How to Provide Configurations ?

Spring provides three main ways for configurations :-


1. XML-based Configuration
2. Java-based Configuration
3. Annotations-based Configuration

1. XML-based Configuration

o This is an older approach where configurations are provided in XML


files (typically [Link]).
o For Example :

<bean class="[Link]" id="stdId">


<property name="name" value="Deepak"/>
<property name="rollno" value="101"/>
<property name="emailid" value="deepak@[Link]"/></bean>

o In this configuration, we are creating one Student Bean


Object and setting the values in properties.
o Advantages: XML Based Configurations allows a clear separation of
configuration from code, which is useful for complex applications or
when working with legacy codebases.
o Disadvantages: XML Based Configurations are very long and can get
hard to manage as it grows. Also it doesn't support helpful code
suggestions or catch errors easily in the IDE.

o This is somewhat new approach where configurations are provided in


Java Class using @Configuration and @Bean annotations.
o For Example :

@Configuration
publicclassAppConfig{
@Bean
publicStudentstdId()
{
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

returnnewStudent("Deepak");
}}

In this configuration, we create creating one Student


o
Bean Object and setting the values using constructor.
o Advantages: Java Based Configurations provides Type safety, better
readability and IDE support. It allows configuration to stay within the
code, making it easier to understand for developers familiar with the
Java language.
o Disadvantages: Java Based Configurations can mix the configuration
with business logic, potentially cluttering code.

3. Annotations-based Configuration

o This is modern approach where configurations are provided directly on


components and classes using annotations i.e. @Component,
@Controller, @Service, @Repository etc
o For Example :

@Component
publicclassStudent{
privateString name ="Deepak";}
//-----------
@Autowired
privateStudent student;

o
o Advantages: Annotations Based Configurations requires minimal
configurations, making it suitable for simpler applications or services.
It promotes cleaner code by removing external configuration files.
o Disadvantages: Annotations Based Configurations have limited
flexibility for complex bean [Link] are less explicit, which
may be confusing in large projects with numerous dependencies

Spring Bean Life Cycle


CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

Introduction

• In Spring, beans are the backbone of our application. They represent the
objects that we have to create and manage within the Spring context.
• These beans go through a well-defined life cycle, where Spring handles
everything from their creation to their destruction.
• Different stages of Bean Life Cycle are as below :-
1. Loading Bean Definitions : Spring reads the configuration (XML,
Java, or annotations) to understand how to create and configure beans,
including their properties and dependencies.
2. Bean Instantiation : Spring creates bean instances using constructors
or factory methods. Then dependencies are injected through
constructor OR setter OR property injection.
3. Bean Initialization : After bean is instantiated and its properties are
set, Spring performs initialization by calling an init() method OR
afterPropertiesSet() method (from the InitializingBean interface) OR
@PostConstruct annotation.
4. Bean Usage : The fully initialized bean is now ready for use. It can
interact with other beans or components in the application.
5. Bean Destruction : Upon container shutdown, Spring destroys the
bean. This can be done via custom destroy() method OR
DisposableBean (interface) OR @PreDestroy annotation for cleanup.

• Below is the diagram representing Bean Life Cycle :-

Above Bean Life Stages are explained deeply as below :-


1. Loading Bean Definitions :

• What Happens: Spring first reads and understands the definitions of all the
beans in the application. These definitions are like blueprints that tell Spring
how to create and configure beans.
• Where Definitions Come From: These configurations can be provided by
different ways as below:
o XML Configuration: In the old days, beans were defined in XML
files.
o Java Configuration: With the rise of Java-based configuration, we
can define beans using @Configuration and @Bean annotations.
o Annotations: With annotations like @Component, @Service, etc., we
can let Spring automatically discover and register beans.
• What Spring Understands: In this stage, Spring knows the class of each
bean, its properties (like name, rollno, emailid in Student class) and its
dependencies (other beans it needs).
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

2. Bean Instantiation :

• What Happens: Once Spring knows what beans it needs to create, it creates
instances of those beans. This is the instantiation phase.
• How Beans Are Created: Beans can be created by different ways as below:
o Default Constructor: A no-argument constructor is used.
o Static Factory Method: A static method on a class that returns an
instance of the bean.
o Instance Factory Method: A non-static method on a separate factory
class.
• Dependency Injection: During instantiation, dependencies are injected into
the bean. This can be done in three ways:

1. Constructor Injection: Dependencies are provided through the


constructor.
2. Setter Injection: Dependencies are set using setter methods.
3. Property Injection: Dependencies are set using XML tags or
annotations like @Value (in Java-based config).

• Example: If we configure a Student bean with name, rollno, and emailid,


Spring injects the property values (like name Deepak, rollno 102 and email id
as deepak@[Link] in this example) in this phase (e.g., through setter
methods or annotations).

3. Bean Initialization :

• What Happens: After a bean is created, it’s initialized by setting its


properties to their configured values. This is where any external dependencies,
such as values from a configuration file, are injected into the bean.
• Different Ways to Initialize: Beans are initialized by different ways as below:

o Using init() method: We can define a custom initialization method in


our bean.
o Using afterPropertiesSet(): This method from the InitializingBean
interface is called to perform any necessary initialization.
o Using @PostConstruct: A special annotation that indicates a method
to be run after all properties are set.

• Example: Here the bean is prepared for use. This includes setting properties
(if not already done in instantiation), performing validation, setting up
database connections, initializing caches, configuring logging, and executing
any custom initialization logic such as loading configuration files or
establishing network connections.
• Additional Functionality:

o Aware Interfaces: If the bean implements special interfaces, it can


access the container or its environment. For example:

▪ BeanNameAware: Allows the bean to know its own name.


CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

▪ ApplicationContextAware: Provides access to the Spring


ApplicationContext.
▪ BeanFactoryAware: Gives access to the BeanFactory (for bean
creation).

• Optional Customizations: At this point, we can also use BeanPostProcessor


to add custom logic before and after the bean’s initialization. This is useful for
advanced scenarios like modifying beans dynamically or adding cross-cutting
concerns (e.g., logging or security).

4. Bean Usage :

• What Happens: Now that the bean is initialized, it’s ready to be used. Other
beans or components in the Spring application can access and use this bean.
The bean is fully functional and serves its purpose in the application.

5. Bean Destruction :

• What Happens: When the application shuts down or the Spring container is
closed, Spring cleans up by destroying the beans.
• How Beans Are Destroyed:

o Using destroy() method: We can define a custom destruction method


in the bean.
o Using DisposableBean interface: This interface provides a destroy()
method to clean up resources when the bean is no longer needed.
o Using @PreDestroy annotation: This annotation marks a method to
be called before the bean is destroyed.

• Optional Aspects: If the bean doesn't require any special clean-up, Spring
will skip these methods.

Dependency Injection (DI) in Spring


CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

DI Introduction

• Dependency Injection is a "Design Pattern" that is used to implement


IoC(Inversion of Control) principal.
• Dependency Injection (DI) is a technique where one object (known as the
dependency) is "injected" into another object (the dependent object).
• Below is the simple diagram showing dependency injection in which Address
object is "injected" int Student object:

Here Student (dependent object) depends on Address (injected dependency),


thus injecting Address in Student is known as "Dependency Injection".

• In Spring, Dependency Injection is commonly called "wiring" because it


involves connecting or "wiring" components with their required dependencies.

Purpose of DI

• The primary goal of DI is to decouple classes from each other, making them
easier to manage, test, and reuse.
• Decoupling classes means reducing or removing direct dependencies between
them. In other words, classes don’t directly depend on specific
implementations of other classes but rely on abstractions or interfaces instead.
This separation allows each class to function independently, making the code
more flexible, modular, and easier to maintain.
When classes are decoupled, changes in one class (such as updating or
replacing it) are less likely to impact other classes, which helps in testing,
managing and reusing code across different parts of the application.

Advantages of DI
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

1. Loose Coupling: Classes rely on interfaces or abstract definitions instead of


specific implementations, making it easy to swap out parts without affecting
other parts.
2. Improved Testability: Dependencies can be replaced with mock versions,
which makes it easier to isolate and test each class by itself.
3. Flexibility and Maintainability: Since dependencies are provided from the
outside, we can change them without altering the actual class, making it easy
to update or reconfigure behavior.
4. Easier Configuration Management: Spring’s configuration files or
annotations allow you to define and manage all dependencies in one place,
simplifying setup and changes.
5. Lifecycle Management: Spring takes care of creating, initializing, and
destroying objects (beans) as needed, so you don’t have to manage these
stages manually.

DI Mechanisms

DI Mechanisms means different ways by which dependencies are injected into beans.
Spring provides three DI mechanisms which are as follows:

1. Constructor Injection:

o In Constructor Injection, dependencies are provided through the class


constructor.
o It makes sure that all the necessary parts (dependencies) are provided
as soon as the object is created, so it’s ready to use.
o It is best suited when dependencies are mandatory and should not be
modified after object creation.

2. Setter Injection:

o In Setter Injection, dependencies are injected through public setter


methods after the object is created.
o It allows optional dependencies and supports mutable dependencies
that can be changed after creation.

3. Field Injection (Not Recommended in Spring, but supported with


@Autowired):

o In Field Injection, dependencies are injected directly into fields.


o It is commonly used in frameworks that support reflection-based
injection, but makes testing and managing dependencies harder in
Spring.
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

o Spring promotes constructor or setter injection as compared to field


injection for better testability and clarity.

DI Mechanism sometimes known as DI techniques or DI Methods.

package [Link];

import [Link];

@Component // Marks this class as a Spring-managed beanpublic class Address {

private String city = "Pune";

private String state = "Maharashtra";

// Constructor

public Address() {}

// Getters

public String getCity()

return city;

public String getState()

return state;

@Override

public String toString()

return city + ", " + state;


CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

}}

"Student" class annotated with @Component and used @Autowired for dependency
on Address.

[Link]

[Link];

[Link];importor
[Link];

@Component

// Marks this class as a Spring-managed bean

publicclassStudent{

privateString name ="Deepak";

privateAddress address;// Dependency

// Constructor Injection

@Autowired// Indicates that Spring should inject Address here

publicStudent(Address address)

[Link] = address;

// Getter methods

publicStringgetName()

return name;

}
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

publicAddressgetAddress()

return address;

@Override

publicStringtoString()

return"Student Name: "+ name +", Address: "+ address;

}}

• "AppConfig" class which is configuration class and here we


will scan the package.

[Link]

[Link];

[Link];importor
[Link];

@Configuration

@ComponentScan(basePackages="[Link]")

publicclassAppConfig{

// No explicit bean definitions needed; @Component classes will


be auto-detected}

• "MainApp" class in which we will start the container and


execute the program.

[Link]
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

[Link];

[Link];

[Link]
tionContext;

[Link];[Link];

publicclassMainApp{

publicstaticvoidmain(String[] args)

// Loading Spring context from annotations

ApplicationContextcontext=newAnnotationConfigApplicationC
ontext([Link]);

// Retrieving the Student bean, which has Address


injected

Student student = [Link]([Link]);

[Link](student);

}}

Below is the output

Output:

Student Name: Deepak, Address: Pune, Maharashtra


CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

Constructor Injection in Spring

Introduction

• Constructor Injection is a form of Dependency Injection where an object’s


dependencies are provided at the time of its creation through its Constructor.

• In Constructor Injection, dependencies are passed as parameters to the class’s


constructor, making them explicit and mandatory for creating the instance.
• This approach ensures that all essential dependencies are provided when
creating an object; if a dependency is not supplied, the object cannot be
instantiated, clarifying the requirements for the class to function properly.

• Now we will create 2 programs for Constructor Injection


1. Using Java Configurations
2. Using XML Configurations

Program 1

• First we will create program using Java Configurations. In this


example we will take 2 classes i.e. Engine & Car. The Car class
depends on the Engine class and The Engine is injected via the Car
constructor.

[Link]

[Link];

[Link];

@ComponentpublicclassEngine{

publicvoidstart()

[Link]("Engine started...");

}}

[Link]

[Link];

[Link];

@ComponentpublicclassCar{
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

privateEngine engine;

// Dependency Injection via Constructor

publicCar(Engine engine)

[Link] = engine;

publicvoiddrive()

[Link]();

[Link]("Car is running...");

}}

NOTE : Its good practice to use final keyword for fields (private final Engine
engine;) that should not change after initialization, especially for dependencies
injected via constructor injection.

[Link]

[Link];

[Link];[Link];[Link]
[Link];[Link]
Scan;[Link];

@Configuration@ComponentScan(basePackages
="[Link]")publicclassAppConfig{

@Bean

publicEngineengine()

{
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

returnnewEngine();// Manually creating the Engine bean

@Bean

publicCarcar()

returnnewCar(engine());// Manually injecting the Engine bean into Car

}}

[Link]

[Link];

[Link];[Link]
[Link];

[Link];[Link];

publicclassMainApp{

publicstaticvoidmain(String[] args)

// Loading Spring context from annotations

ApplicationContext context
=newAnnotationConfigApplicationContext([Link]);

Car car = [Link]([Link]);

[Link]();

}}
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

elow is the output


Output:
Engine started...
Car is running..
Program 2

Now we are going to create above same program for Constructor Injection using
XML Configurations.

[Link]

[Link];

publicclassEngine{

publicvoidstart()

[Link]("Engine started...");

}}

[Link]

[Link];

publicclassCar{

privatefinalEngine engine;

// Dependency Injection via Constructor

publicCar(Engine engine)

[Link] = engine;

}
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

publicvoiddrive()

[Link]();

[Link]("Car is running...");

}}

NOTE : Its good practice to use final keyword for fields (private final Engine
engine;) that should not change after initialization, especially for dependencies
injected via constructor injection.

[Link]

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


xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="[Link]

[Link]
[Link]">

<!-- Engine bean -->

<bean id="engine" class="[Link]" />

<!-- Car bean with constructor injection for Engine -->

<bean id="car" class="[Link]">

<constructor-arg ref="engine" />

</bean>

</beans>
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

NOTE : Here we have used <constructor-arg ref="----" /> tag for Constructor
Injection.

[Link]

[Link];

[Link];[Link]
[Link];

[Link];

publicclassMainApp{

publicstaticvoidmain(String[] args)

// Loading Spring context from annotations

ApplicationContext context
=newClassPathXmlApplicationContext("in/sp/resources/[Link]
");

Car car = [Link]([Link]);

[Link]();

}}

Below is the output


Output:
Engine started...
Car is running...
Advantages of Constructor Injection

• Immutability: Constructor Injection allows setting dependencies only once, at


construction, which promotes immutability.
• Clarity: CDI clearly communicates that a class requires certain dependencies
to function, making the code self-documenting.
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

• Reliability: As dependencies are initialized once during object creation, it


reduces the risk of dependencies being altered later, which enhances code
reliability.
• Easier Testing: CDI simplifies testing by allowing mocks to be injected
during test setup.

Setter Method Injection in Spring

Introduction

• Setter Method Injection is a form of Dependency Injection where an object’s


dependencies are provided through setter methods after the object’s creation.

• In Setter Method Injection, dependencies are passed via public setter methods,
making them optional and allowing flexibility in providing or changing
dependencies after the object has been created.
• This approach allows dependencies to be injected or modified after
instantiation. If a dependency is not supplied, the object can still be created but
might not function fully until all necessary dependencies are set.

• Now we will create 2 programs for Setter Method Injection


1. Using Java Configurations
2. Using XML Configurations

Program 1

First we will create program using Java Configurations. In this example we will take 2
classes i.e. Engine & Car. The Car class depends on the Engine class and The Engine
is injected via setter method in Car class.

[Link];

[Link];

@Component

publicclassEngine{

publicvoidstart()

[Link]("Engine started...");

}}


CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

[Link]

[Link];

[Link];

@ComponentpublicclassCar{

privateEngine engine;// Engine dependency

// Setter method for dependency injection

publicvoidsetEngine(Engine engine)

[Link] = engine;

publicvoiddrive()

[Link]();

[Link]("Car is running...");

}}

NOTE : Do not use final keyword for fields (i.e. private final Engine
engine;) like we used for constructor injection because the nature of final
conflicts with the behavior of setter injection.


CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

[Link]

[Link];

[Link];[Link];[Link]
[Link];[Link]
[Link];[Link]
guration;

@Configuration@ComponentScan(basePackages
="[Link]")publicclassAppConfig{

@Bean

publicEngineengine()

returnnewEngine();// Manually creating the Engine bean

@Bean

publicCarcar()

Car car =newCar();// Creating Car bean manually

[Link](engine());// Manually setting the Engine dependency


through setter

return car;

}}


CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

[Link]

[Link];

[Link];[Link]
[Link];

[Link];[Link];

publicclassMainApp{

publicstaticvoidmain(String[] args)

// Loading Spring context from annotations

ApplicationContext context
=newAnnotationConfigApplicationContext([Link]);

Car car = [Link]([Link]);

[Link]();

}}

Output:

Engine started...
Car is running...
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

Program 2

[Link]

[Link];

publicclassEngine{

publicvoidstart()

[Link]("Engine started...");

}}

[Link]

[Link];

publicclassCar{

privateEngine engine;

// Dependency Injection via Setter Method

publicvoidsetEngine(Engine engine)

[Link] = engine;

publicvoiddrive()
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

[Link]();

[Link]("Car is running...");

}}

[Link]

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


xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="[Link]

[Link]
[Link]">

<!-- Engine bean -->

<bean id="engine" class="[Link]" />

<!-- Car bean with setter injection for Engine -->

<bean id="car" class="[Link]">

<property name="engine" ref="engine" />

</bean>

</beans>


CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

NOTE : Here we have used <property name="----" ref="----" /> tag for
Setter Method Injection.

[Link]

[Link];

[Link];[Link]
[Link];

[Link];

publicclassMainApp{

publicstaticvoidmain(String[] args)

// Loading Spring context from XML configuration

ApplicationContext context
=newClassPathXmlApplicationContext("in/sp/resources/applicationCont
[Link]");

Car car = [Link]([Link]);

[Link]();

}}

Output:

Engine started...
Car is running...
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

Advantages of Setter Method Injection

• Flexibility: Setter Method Injection allows dependencies to be changed or


updated after object creation, which can be useful if we need to reconfigure
dependencies at runtime or in specific scenarios.
• Optional Dependencies: Setter injection makes it easy to declare optional
dependencies. Unlike Constructor Injection, which requires all dependencies
to be provided at instantiation, Setter Injection allows for dependencies to be
set only if needed.
• Better Handling of Circular Dependencies: In complex applications, Setter
Injection can help manage circular dependencies more gracefully, as objects
can be created first and dependencies injected later.
• Ease of Reconfiguration: Since dependencies can be modified after object
creation, Setter Injection is well-suited for situations where dependencies
might vary based on context or conditions.
• Supports Legacy Code: Setter Injection can be more convenient when
integrating with legacy code or frameworks that do not allow modification of
existing constructors, as it enables dependency injection without altering the
constructor signature.

Autowiring in Spring

Introduction

• Autowiring in Spring is a powerful feature that allows Spring


to automatically inject dependencies into a bean without needing explicit
configuration.
• It is a part of dependency injection concept, which is central to Spring's
Inversion of Control (IoC) container.

• Note : Autowiring can't be used to inject primitive and string values. It works
with reference only.

• The main advantage of autowiring is that it :-


o Promotes loose coupling.
o Reduces boilerplate code.
o Makes applications easier to maintain.

• The main disadvantage of autowiring is that :-

o If multiple beans of the same type are present, it can lead to ambiguity,
making dependency management harder and causing runtime errors.
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

• There are 3 types of Dependency Injection Mechanisms and autowiring in


Spring also follows these same mechanisms to inject dependencies
automatically.

o Constructor Injection :

▪ Definition : In this, dependencies are injected through the


constructor of the class. Spring automatically passes the
required dependencies when the bean is instantiated.
▪ When to Use : We should use constructor injection when the
dependencies are mandatory and must be provided during the
object's creation. It's ideal for immutable objects where the
dependencies cannot change after bean creation.

o Setter Injection :

▪ Definition : In this, dependencies are injected through setter


methods after the bean is created. Spring calls the setter
methods to inject the required dependencies.
▪ When to Use : We should use use setter injection when
dependencies are optional or can be set after the object is
created. It is useful when dependencies might change later or
when dealing with circular dependencies.

o Field Injection (also called Direct Injection) :


▪ Definition : In this, dependencies are injected directly into the
fields of the class using the @Autowired annotation, without
using constructors or setter methods.
▪ When to Use : We should use use field injection for simple and
concise code when the dependencies do not need to change and
are easy to manage. It is suitable for smaller projects or cases
where minimal configuration is needed.

How to achieve autowiring :

We can achieve autowiring using "autowire attribute" and "@Autowired annotation"


which are explained below :-

1. XML-based Configuration:

o It is achieved by using the autowire attribute in the <bean> tag.


o Click here for Autowiring in XML-based Configuration with Program.
o Note : If multiple beans of the same type are available for dependency
injection, we can use the autowire-candidate="false" attribute in the
bean definition to exclude a particular bean from being considered as
an autowire candidate, ensuring Spring selects the appropriate bean for
injection.

2. Java & Annotation based Configuration:


CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

o It is achieved using @Autowired annotation on constructors, setter


methods or fields.
o Click here for Autowiring in Java & Annotation based Configuration
with Program.
o Note : If multiple beans of the same type are available for dependency
injection, then we use @Qualifier or @Primary annotations.

Spring Autowiring Java @Autowired

Introduction

• In Java & Annotation based configuration, autowiring is achieved using


the @Autowired annotation either on constructor or setter method or fields.
• The Spring container automatically resolves and injects dependencies where
the @Autowired annotation is applied.

• By using @Autowired annotation, we dont need to use autowire attribute in


the <bean> tag.

• Now we will create some programs of Autowiring using Java & Annotation
based Configuration.

Program 1

First we will create program using Java Configurations with @Autowired Annotation
which is applied on constructor.

[Link]

[Link];

publicclassEngine{

publicvoidstart()

[Link]("Engine started...");

}}

[Link]

[Link];
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

[Link];[Link]
[Link];

@ComponentpublicclassCar{

privateEngine engine;

// Constructor for dependency injection

@Autowired

publicCar(Engine engine)

[Link] = engine;

publicvoiddrive()

[Link]();

[Link]("Car is running...");

}}

[Link]

[Link];

[Link];[Link].
[Link];[Link]
[Link];

[Link];

@Configuration@ComponentScan(basePackages
="[Link]")publicclassAppConfig{
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

@Bean

publicEngineengine()

returnnewEngine();

}}

[Link]

[Link];

[Link];[Link]
[Link];

[Link];[Link];

publicclassMainApp{

publicstaticvoidmain(String[] args)

// Load Spring context using Java configuration

ApplicationContext context
=newAnnotationConfigApplicationContext([Link]);

// Retrieve the Car bean

Car car = [Link]([Link]);

// Call the drive method

[Link]();

}}

Below is the output


CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

Output:
Engine started...
Car is running...
Program 2

Now we are going to create program using Java Configurations


with @Autowired Annotation which is applied on setter methods.

[Link]

[Link];

publicclassEngine{

publicvoidstart()

[Link]("Engine started...");

}}

[Link]

[Link];

[Link];[Link]
[Link];

@ComponentpublicclassCar{

privateEngine engine;

// Setter method for dependency injection

@Autowired

publicvoidsetEngine(Engine engine)

[Link] = engine;
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

publicvoiddrive()

[Link]();

[Link]("Car is running...");

}}

[Link]

[Link];

[Link];[Link].
[Link];[Link]
[Link];

[Link];

@Configuration@ComponentScan(basePackages ="[Link]")// Scans for


@Component-annotated classespublicclassAppConfig{

@Bean

publicEngineengine()

returnnewEngine();

}}

[Link]

[Link];

[Link];[Link]
[Link];

[Link];
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

publicclassMainApp{

publicstaticvoidmain(String[] args)

// Loading Spring context from annotations

ApplicationContext context
=newClassPathXmlApplicationContext("in/sp/resources/[Link]
");

Car car = [Link]([Link]);

[Link]();

}}

Below is the output


Output:
Engine started...
Car is running...
Program 3

Now we will create third program using Java Configurations


with @Autowired Annotation which is applied on fields.

[Link]

[Link];

publicclassEngine{

publicvoidstart()

[Link]("Engine started...");

}}
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

[Link]

[Link];

[Link];[Link]
[Link];

@ComponentpublicclassCar{

@Autowired

privateEngine engine;// Field injection with @Autowired

publicvoiddrive()

[Link]();

[Link]("Car is running...");

}}

[Link]

[Link];

[Link];[Link].
[Link];[Link]
[Link];

[Link];

@Configuration@ComponentScan(basePackages
="[Link]")publicclassAppConfig{

@Bean

publicEngineengine()

returnnewEngine();
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

}}

[Link]

[Link];

[Link];[Link]
[Link];

[Link];[Link];

publicclassMainApp{

publicstaticvoidmain(String[] args)

// Load Spring context using Java configuration

ApplicationContext context
=newAnnotationConfigApplicationContext([Link]);

// Retrieve the Car bean

Car car = [Link]([Link]);

// Call the drive method

[Link]();

}}

Below is the output


Output:
Engine started...
Car is running..
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

Commonly used Spring Boot annotations along with their uses and
examples

1). @SpringBootApplication: This annotation is used to bootstrap a


Spring Boot application. It combines three
annotations: @Configuration, @EnableAutoConfiguration,
and @ComponentScan.

Example:

@SpringBootApplicationpublicclassMyApplication{

publicstaticvoidmain(String[] args){

[Link]([Link], args);

}}

2). @RestController: This annotation is used to indicate that a class is a


RESTful controller. It combines @Controller and @ResponseBody.

Example:

@RestController

publicclassMyController{

@GetMapping("/hello")

publicStringhello(){

return"Hello, World!";

}}

3). @RequestMapping: This annotation is used to map web requests to


specific handler methods. It can be applied at the class or method level.

Example:
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

@RestController

@RequestMapping("/api")

publicclassMyController{

@GetMapping("/hello")

publicStringhello(){

return"Hello, World!";

}}

4). @Autowired: This annotation is used to automatically wire


dependencies in Spring beans. It can be applied to fields, constructors, or
methods.

Example:

@ServicepublicclassMyService{

privateMyRepository repository;

@Autowired

publicMyService(MyRepository repository){

[Link] = repository;

}}

5). @Component: This annotation is used to indicate that a class is a


Spring bean. Example:

@ComponentpublicclassMyComponent{

// ...}

6). @Service: This annotation is used to indicate that a class is a


specialized type of Spring bean, typically used for business logic.
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

Example:

@Service

publicclassMyService{

// ...}

7). @Repository: This annotation is used to indicate that a class is a


specialized type of Spring bean, typically used for database access.

Example:

@Repository

publicclassMyRepository{

// ...}

8). @Configuration: This annotation is used to declare a class as a


configuration class. It is typically used in combination
with @Bean methods.

Example:

@Configuration

publicclassMyConfiguration{

@Bean

publicMyServicemyService(){

returnnewMyService();

}}

9). @Value: This annotation is used to inject values from properties files
or other sources into Spring beans.

Example:
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

@Component

publicclassMyComponent{

@Value("${[Link]}")

privateString myProperty;}

10). @EnableAutoConfiguration: This annotation is used to enable


Spring Boot’s auto-configuration mechanism. It automatically configures
the application based on the classpath dependencies and properties.

Example:

@SpringBootApplication

@EnableAutoConfiguration

publicclassMyApplication{

// ...}

11). @GetMapping, @PostMapping, @PutMapping,


@DeleteMapping: These annotations are used to map specific HTTP
methods to handler methods. They are shortcuts
for <strong>@RequestMapping</strong> with the respective HTTP
method.

Example:

@RestController

@RequestMapping("/api")

publicclassMyController{

@GetMapping("/hello")

publicStringhello(){

return"Hello, World!";
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

@PostMapping("/data")

publicvoidsaveData(@RequestBodyData data){

// Save data

}}

12). @PathVariable: This annotation is used to bind a method


parameter to a path variable in a request URL.

Example:

@RestController@RequestMapping("/api")publicclassMyController{

@GetMapping("/users/{id}")

publicUsergetUser(@PathVariableLong id){

// Retrieve user with the given ID

}}

13). @RequestParam: This annotation is used to bind a method


parameter to a request parameter.

Example:

@RestController@RequestMapping("/api")publicclassMyController{

@GetMapping("/users")

publicList<User>getUsers(@RequestParam("status")String status){

// Retrieve users with the given status

}}
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

14). @RequestBody: This annotation is used to bind the request body to


a method parameter. It is commonly used in RESTful APIs to receive
JSON or XML payloads. Example:

@RestController@RequestMapping("/api")publicclassMyController{

@PostMapping("/users")

publicvoidcreateUser(@RequestBodyUser user){

// Create a new user

}}

15). @Qualifier: This annotation is used to specify which bean to inject


when multiple beans of the same type are available.

Example:

@Service@Qualifier("myService")publicclassMyService{

// ...}

@ServicepublicclassAnotherService{

@Autowired

@Qualifier("myService")

privateMyService myService;

// ...}

16). @ConditionalOnProperty: This annotation is used to conditionally


enable or disable a bean or configuration based on the value of a
property.

Example:

@Configuration@ConditionalOnProperty(name ="[Link]",
havingValue ="true")publicclassMyConfiguration{
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

// Configuration for the feature when enabled}

17). @Scheduled: This annotation is used to schedule the execution of a


method at fixed intervals.

Example:

@ComponentpublicclassMyScheduler{

@Scheduled(fixedDelay =5000)

publicvoiddoSomething(){

// Perform a task periodically

}}

18). @Cacheable, @CachePut, @CacheEvict: These annotations are


used for caching method results. They allow you to cache the return
value of a method, update the cache, or evict the cache, respectively.

Example:

@ServicepublicclassMyService{

@Cacheable("users")

publicUsergetUserById(Long id){

// Retrieve user from database

@CachePut("users")

publicUserupdateUser(User user){

// Update user in database and cache

}
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

@CacheEvict("users")

publicvoiddeleteUser(Long id){

// Delete user from database and remove from cache

}}

Here’s an extensive list of Spring Boot annotations

1. Core Annotations:

a). @SpringBootApplication

The @SpringBootApplication annotation is used to mark the main class


of a Spring Boot application. This is the Spring Boot Application starting
point. It combines three
annotations: @Configuration, @EnableAutoConfiguration,
and @ComponentScan. This annotation enables auto-configuration,
component scanning, and configuration capabilities for the application.

Example:

@SpringBootApplicationpublicclassMyApp{

publicstaticvoidmain(String[] args){

[Link]([Link], args);

}}

b). @ComponentScan

The @ComponentScan annotation is used to specify the base package(s)


to scan for Spring components such as controllers, services, repositories,
etc.
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

Example:

@ComponentScan("[Link]")@ConfigurationpublicclassA
ppConfig{

// Configuration code here}

c). @Configuration

The @Configuration annotation is used to indicate that a class declares


one or more bean definitions. It is typically used in combination
with @Bean to define Spring configuration classes. In the example,
the DatabaseConfig class is marked as a configuration class, and
the dataSource() method is annotated with @Bean to define a bean of
type DataSource.

d). @EnableAutoConfiguration

The @EnableAutoConfiguration annotation allows Spring Boot to


automatically configure the application based on the dependencies
present in the classpath. It helps to reduce manual configuration by
inferring configuration based on conventions and default settings.

e). @RestController

The @RestController annotation is used to mark a class as a controller in


a Spring MVC or Spring WebFlux application. It combines
the @Controller and @ResponseBody annotations. In the example,
the UserController class is a REST controller that handles HTTP GET
requests for the “/users” endpoint.

f). @Controller
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

The @Controller annotation is used to mark a class as a controller in a


Spring MVC or Spring WebFlux application. It handles HTTP requests
and returns the view name or a response body. In the example,
the HomeController class is a controller that handles requests for the root
(“/”) URL and returns the view name “index”.

g). @Service

The @Service annotation is used to mark a class as a service component


in the business logic layer. It is used to encapsulate business logic and
perform operations such as data retrieval, manipulation, and validation.
In the example, the UserService class is a service component that
provides a method to retrieve users.

h). @Repository

The @Repository annotation is used to mark a class as a repository


component in the data access layer. It is responsible for data access
operations such as querying, saving, updating, and deleting data from a
database. In the example, the UserRepository class is a repository
component that provides a method to retrieve users from the database.

i). @Bean

The @Bean annotation is used to declare a method as a bean producer


method within a configuration class. It indicates that the method returns
an object that should be managed by the Spring container as a bean. In
the example, the userService() method is annotated with @Bean to
define a bean of type UserService.

j). @Autowired
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

The @Autowired annotation is used to inject dependencies automatically


by type. It can be applied to constructors, fields, and methods. In the
example, the UserRepository dependency is autowired into
the UserService class constructor.

k). @Qualifier

The @Qualifier annotation is used to resolve ambiguous dependencies


when there are multiple beans of the same type. It can be applied along
with @Autowired to specify the exact bean to be injected. In the
example, the userRepository bean is qualified using its bean name.

l). @Value

The @Value annotation is used to inject values from external sources,


such as properties files, into variables. In the example, the appName the
variable is injected with the value of the “[Link]” property from an
external configuration source.

2. Web Annotations:

@RequestMapping

@GetMapping

@PostMapping

@PutMapping

@DeleteMapping

@PatchMapping

@RequestBody
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

@ResponseBody

@PathVariable

@RequestParam

@RequestHeader

@CookieValue

@ModelAttribute

@ResponseStatus

@ExceptionHandler

3. Data Annotations:

@Entity

@Table

@Id

@GeneratedValue

@Column

@Transient

@Repository

@Service

@Transactional

@PersistenceContext
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

@Autowired

@Query

@NamedQuery

@Param

@JoinTable

@JoinColumn

4. Validation Annotations:

@Valid

@NotNull

@Size

@Min

@Max

@Email

@Pattern

5. Security Annotations:

@EnableWebSecurity

@Configuration

@EnableGlobalMethodSecurity

@PreAuthorize
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

@PostAuthorize

@Secured

@RolesAllowed

@EnableOAuth2Client

@EnableResourceServer

@EnableAuthorizationServer

6. Testing Annotations:

@RunWith

@SpringBootTest

@WebMvcTest

@DataJpaTest

@RestClientTest

@MockBean

@AutoConfigureMockMvc

@Test

@Before

@After

@BeforeEach

@AfterEach
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

@BeforeAll

@AfterAll

@DisplayName

@Disabled

@ParameterizedTest

@ValueSource

@CsvSource

@ExtendWith

7. Caching Annotations:

@EnableCaching

@Cacheable

@CachePut

@CacheEvict

@Caching

8. Scheduling Annotations:

@EnableScheduling

@Scheduled

9. Messaging Annotations:

@EnableJms
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

@JmsListener

@SendTo

@MessageMapping

@Payload

@Header

10. Aspect-Oriented Programming (AOP) Annotations:

@Aspect

@Pointcut

@Before

@After

@AfterReturning

@AfterThrowing

@Around

11. Actuator Annotations:

@EnableActuator

@Endpoint

@RestControllerEndpoint

@ReadOperation

@WriteOperation
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

@DeleteOperation

12. Configuration Properties Annotations:

@ConfigurationProperties

@ConstructorBinding

@Validated

13. Internationalization and Localization:

@EnableMessageSource

@EnableWebMvc

@LocaleResolver

@MessageBundle

@MessageSource

14. Logging and Monitoring:

@Slf4j

@Log4j2

@Log

@Timed

@Counted

@ExceptionMetered

15. Data Validation:


CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

@Validated

@Valid

@Validated

@NotNull

@NotBlank

@Email

@Size

@Pattern

@Positive

@PositiveOrZero

@Negative

@NegativeOrZero

16. GraphQL Annotations:

@GraphQLApi

@GraphQLQuery

@GraphQLMutation

@GraphQLSubscription

@GraphQLArgument

@GraphQLContext
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

@GraphQLNonNull

@GraphQLInputType

@GraphQLType

17. Integration Annotations:

@IntegrationComponentScan

@MessagingGateway

@Transformer

@Splitter

@Aggregator

@ServiceActivator

@InboundChannelAdapter

@OutboundChannelAdapter

@Router

@BridgeTo

18. Flyway Database Migrations:

@FlywayTest

@FlywayTestExtension

@[Link]

@[Link]
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

@[Link]

19. JUnit 5 Annotations:

@ExtendWith

@TestInstance

@TestTemplate

@DisplayNameGeneration

@Nested

@Tag

@DisabledOnOs

@EnabledOnOs

@DisabledIf

@EnabledIf

20. API Documentation Annotations:

@Api: This annotation is used to provide high-level information about


the API.

@ApiOperation: This annotation is used to describe an operation or


endpoint in the API.

@ApiParam: This annotation is used to describe a parameter in an API


operation.

@ApiModel: This annotation is used to describe a data model used in the


API.
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

@ApiModelProperty: This annotation is used to describe a property of a


data model.

21. Exception Handling Annotations:

@ControllerAdvice: This annotation is used to define global exception


handling for controllers.

@ExceptionHandler: This annotation is used to define a method to


handle specific exceptions.

22. GraphQL Annotations:

@GraphQLSchema: This annotation is used to define the GraphQL


schema for a Spring Boot application.

@GraphQLQueryResolver: This annotation is used to define a class as a


GraphQL query resolver.

@GraphQLMutationResolver: This annotation is used to define a class


as a GraphQL mutation resolver.

@GraphQLSubscriptionResolver: This annotation is used to define a


class as a GraphQL subscription resolver.

@GraphQLResolver: This annotation is used to define a class as a


generic resolver for GraphQL.

23. Server-Sent Events (SSE) Annotations:

@SseEmitter: This annotation is used to create an SSE endpoint for


server-sent events.

@SseEventSink: This annotation is used to inject an SSE event sink into


a method parameter.
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

24. WebFlux Annotations:

@RestController: This annotation is used to create a RESTful controller


in a WebFlux application.

@GetMapping, @PostMapping, @PutMapping, @DeleteMapping,


@PatchMapping: These annotations are used to map HTTP methods to
handler methods in a WebFlux application.

25. Micrometer Metrics Annotations:

@Timed: This annotation is used to measure the execution time of a


method.

@Counted: This annotation is used to count the number of times a


method is invoked.

@Gauge: This annotation is used to expose a method as a gauge metric.

@ExceptionMetered: This annotation is used to measure the rate of


exceptions thrown by a method.
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

Configure the Spring container for Dependency Injection (DI)

Dependency Injection is configured through the Spring context configuration. Here’s


a basic example using Java configuration:

java
import [Link];
import [Link];
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
@Bean
public MyController myController() {
return new MyController(myService());
}}

Define Spring Beans using the @Component annotation

Annotate your classes with @Component to indicate that they are Spring beans:

java
import [Link];
@Component
public class MyComponent {
// your logic here}

Perform Auto-scanning of Spring Beans to minimize configuration

Enable component scanning by annotating your main application class with


@SpringBootApplication, which includes @ComponentScan:

java
CLOUD COMPUTING FULL STACK DEVELOPMENT-MVJ22CS61

import [Link];
import [Link];
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
[Link]([Link], args);
}}

Automatically wire beans together using @Autowired annotation

Use @Autowired to inject dependencies automatically:

java
import [Link];
import [Link];
@Component
public class MyServiceConsumer {
private final MyService myService;
@Autowired
public MyServiceConsumer(MyService myService) {
[Link] = myService;
}
// use myService in your methods}
RESTful Web Services

RESTful Web Services REST stands for REpresentational State Transfer. It was
developed by Roy Thomas Fielding, one of the principal authors of the web
protocol HTTP. Consequently, REST was an architectural approach designed to
make the optimum use of HTTP protocol. It uses the concepts and verbs already
present in HTTP to develop web services. This made REST incredibly easy to use
and consume, so much so that it is the go-to standard for building web services
today.

A resource can be anything, it can be accessed through a URI (Uniform Resource


Identifier). Unlike SOAP, REST does not have a standard messaging format. We
can build REST web services using many representations, including both XML and
JSON, although JSON is the more popular option. An important thing to consider is
that REST is not a standard but a style whose purpose is to constrain our
architecture to a client-server architecture and is designed to use stateless
communication protocols like HTTP.

Important Methods of HTTP


The main methods of HTTP we build web services for are:

1. GET: Reads an existing data.


2. PUT: Updates existing data.
3. POST: Creates new data.
4. DELETE: Deletes the data.

1. GET

The default request method for HTTP. We don’t have any request body with this
method, but we can define multiple request parameters or path variables in the URL.
This method is used for getting obtaining some resources. Depending on the
presence of an ID parameter, either we can fetch a specific resource or fetch a
collection of resources in the absence of the parameter. Sample GET request in
Spring Boot Controller:
@GetMapping("/user/{userId}")
public ResponseEntity<Object> getUser(@PathVariable int userId) {
UserEntity user = [Link](userId);
return new ResponseEntity<>(user, [Link]);
}

Example of GET operation to perform in an application:

• GET/employees: This will retrieve all employee details.

2. POST

The POST method of HTTP is used to create a resource. We have a request body in
this method and can also define multiple request parameters or path variables in the
URL. Sample POST request in Spring Boot Controller:

@PostMapping(value = "/user")
public ResponseEntity<Object> addUser(@RequestBody UserEntity user) {
[Link](user);
return new ResponseEntity<>("User is created successfully",
[Link]);
}

Example of POST operation to perform in an application:

• POST/employees: This will create an employee.

3. PUT

The PUT method of HTTP is used to update an existing resource. We have a request
body in this method and can also define multiple request parameters or path
variables in the URL. Sample PUT request in Spring Boot Controller:

@PutMapping("/user/{userId}")
public ResponseEntity<Object> getUser(@RequestBody UserEntity user) {
[Link](user);
return new ResponseEntity<>("User is updated successfully", [Link]);
}

Example of PUT operation to perform in an application:

• PUT/employees/{id}: This will update an existing employee’s details.

4. DELETE

The DELETE method of HTTP is used to remove a resource. We don’t have a


request body in this method but can define multiple request parameters or path
variables in the URL. We can delete multiple or single records, usually based on
whether we have an ID parameter or not. We can delete multiple or single records,
usually based on whether we have an ID parameter or not. Sample DELETE request
in Spring Boot Controller:

@DeleteMapping(value = "/user")
public ResponseEntity<Object> addUser(@PathVariable int userId) {
[Link](userId);
return new ResponseEntity<>("User is deleted successfully", [Link]);
}

Example of DELETE operation to perform in an application:

• DELETE/employees: This will delete all employees.


REST web services use the Status-Line part of an HTTP response message to
inform clients of their request’s ultimate result.

HTTP Standard Status Codes


The status codes defined in HTTP are the following:

• 200: Success
• 201: Created
• 401: Unauthorized
• 404: Resource Not Found
• 500: Server Error
Principles of RESTful web services

The following are the main principles rest services follow, which makes them fast,
lightweight, and secure are:

• Resource Identification through URI- A RESTful web service provides an


independent URI/ global ID for every resource.
• Uniform Interface- Resources are manipulated using a fixed set of four
create, read, update, delete operations: PUT, GET, POST, and DELETE.
• Self-descriptive messages- Resources and representations are decoupled in a
RESTful web service. This allows us to represent the payload in various formats
such as HTML, XML, plain text, PDF, JPEG, JSON, and others based on our use
case.
• Stateful Interaction through hyperlinks- Every interaction with a resource is
stateless; that is, request messages are self-contained.

Advantages of RESTful web services

Some of the primary advantages of using RESTful web services are,

• Easy to Build: REST APIs are simpler to build than a corresponding SOAP
API. Hence, REST is the better choice if we want to develop APIs quickly.
• Independent: Since the client and server are decoupled in RESTful web
services, it allows for independent development across projects.
• Scalability: Stateless communication and a replicated repository provide a
high level of scalability. Compared to SOAP, scaling up an existing website is
easier with the REST web services.
• Layered System: REST web services have their application divided into
multiple layers forming a hierarchy. It makes the application both modular and
scalable.
Consuming REST Services in Spring Boot
Spring Boot provides several robust options for consuming RESTful web services. In
this blog post, we will explore three primary methods: RestTemplate, WebClient, and
Feign Client. Each approach offers unique features and benefits suited for different
use cases.

1. RestTemplate
Description: RestTemplate is a synchronous client for performing HTTP requests. It
is simple to use and ideal for applications where synchronous calls are sufficient.
Synchronous client:
This means that the client waits for a response from the server before proceeding with
the next action.

Setup and Usage:

Add Dependency: To use RestTemplate, add the following dependency to your


[Link]:

<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Configuration: Configure RestTemplate as a bean:

@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return [Link]();
}
}
Service Implementation: Use RestTemplate in your service class:

@Service
public class RestTemplateService {
private final RestTemplate restTemplate;

public RestTemplateService(RestTemplate restTemplate) {


[Link] = restTemplate;
}

public String getSomethingFromApi(String url) {


return [Link](url, [Link]);
}
}
2. WebClient
Description: WebClient is a non-blocking, reactive client for performing HTTP
requests. It supports both synchronous and asynchronous operations, making it
ideal for reactive applications.

Setup and Usage:

Add Dependency: To use WebClient, add the following dependency to your


[Link]:

<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

Configuration: Configure WebClient as a bean:

@Configuration
public class WebClientConfig {
@Bean
public [Link] webClientBuilder() {
return [Link]();
}
}
Service Implementation: Use WebClient in your service class:

@Service
public class WebClientService {
private final WebClient webClient;

public WebClientService([Link] webClientBuilder) {


[Link] = [Link]();
}

public Mono<String> getSomethingFromApi(String url) {


return [Link]()
.uri(url)
.retrieve()
.bodyToMono([Link]);
}
}
3. Feign Client
Description: Feign is a declarative web service client that simplifies the process of
writing web service clients by providing a simple, annotation-based API.

Setup and Usage:

Add Dependency: To use Feign, add the following dependency to your [Link]:

<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
Enable Feign Clients: Enable Feign clients in your main application class:

@SpringBootApplication
@EnableFeignClients
public class Application {
public static void main(String[] args) {
[Link]([Link], args);
}
}
Define Feign Client: Define the Feign client interface:

@FeignClient(name = "apiClient", url = "[Link]


public interface ApiClient {
@GetMapping("/endpoint")
String getSomething();
}
Service Implementation: Use the Feign client in your service class:

@Service
public class FeignClientService {
private final ApiClient apiClient;

public FeignClientService(ApiClient apiClient) {


[Link] = apiClient;
}

public String getSomethingFromApi() {


return [Link]();
}
}
Spring Boot - Complete Guide to Validations for REST API’s
Validations:
Validations in Spring Boot are an integral part of building robust and secure REST APIs. They help
ensure that incoming requests contain valid and well-formed data before processing them further

Hibernate Validator
[Link] Validation Dependency
[Link] Validation Constraints in DTO.
[Link] Request Data in Controller
[Link] Validation Error Responses

Dependencies
To use the validation framework in our application we need to add following
dependencies to our project.

<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Bean Validation
Bean Validation works by adding constraint annotations on the fields of the class to
be validated. Commonly used annotations are defined in [Link]
package.

@NotNull: Used when a field must not be null.


@NotEmpty: Used when a list field must not empty.
@NotBlank: Used when a string field must not be the empty string (i.e. it must have
at least one character).
@Min and @Max: Used when a numerical field is only valid when it’s value is
above or below a certain value.
@Pattern: Used when a string field is only valid when it matches a certain regular
expression.
@Email: Used when a string field must be a valid email address.

An example of class with annotations :

1 public class StudentDto {


2
3 @NotBlank(message = "Should not be null or empty.")
4 private String firstName;
5
6 @Email(message = "Not valid.")
7 private String email;
8
9 @Size(min = 4, max = 10, message = "Should be min 4 character and max
10 10 character in length.")
11 private String password;}

Validation of Inputs to a REST Controller:


There are 3 things which are to be validated for a incoming REST request:

[Link] Body
[Link] Variables
[Link] Parameters

[Link]:
Implementing Validations on the Bean

Before we add validations, we need to add a dependency.

<dependency>

<groupId>[Link]</groupId>

<artifactId>spring-boot-starter-validation</artifactId>

</dependency>

Let’s add a few validations to the Student bean. We are using @Size to specify the
minimum length and also a message when a validation error occurs.

public ResponseEntity<Object> createStudent(@Valid @RequestBody Student


student) {

@Entity

public class Student {

@Id

@GeneratedValue

private Long id;

@NotNull

@Size(min=2, message="Name should have atleast 2 characters")

private String name;

@NotNull
@Size(min=7, message="Passport should have atleast 2 characters")

private String passportNumber;

• The @Valid annotation ensures that the Student object is validated against the
constraints specified in the Student class before the controller's logic is executed.

• If validation fails (e.g., a field does not meet the constraints), Spring will throw a
MethodArgumentNotValidException. You can handle this exception globally to
return custom error messages

@Entity Annotation

This marks the Student class as a JPA Entity, meaning it maps to a table in a
database.

• By default, the table name corresponds to the class name (Student), but you can
customize it using the @Table annotation.

• @Id: Specifies that the id field is the primary key of the Student entity.

• @GeneratedValue: Automatically generates unique values for the id field. The


default generation strategy is used unless explicitly specified.

• Ensures that the name and passportNumber fields cannot be null.

• If a client sends a JSON object without the name or passportNumber fields,


validation will fail.

• @Size: Validates the length of a String, Collection, Map, or Array.

min=2: The name field must have at least 2 characters.

min=7: The passportNumber field must have at least 7 characters.

• message: The custom message returned to the client when validation fails.

Enabling Validation on the Resource

The @GeneratedValue annotation in Java's JPA (Java Persistence API) is used to specify how the
primary key (annotated with @Id) of an entity should be automatically generated
Simple. Add @Valid in addition to @RequestBody.

public ResponseEntity<Object> createStudent(@Valid @RequestBody Student


student) {

It automatically converts JSON or XML data from the request body into a Java object
When you execute a request with attributes not matching the constraint, you get a 404
BAD Request status back.
Request

"name": "",

"passportNumber": "A12345678"

Customizing Validation Response

Let’s define a simple error response bean.


public class Student {

@NotNull(message = "Name is mandatory")

@Size(min = 2, message = "Name must be at least 2 characters long")

private String name;

@NotNull(message = "Passport number is required")

@Size(min = 7, message = "Passport number must be at least 7 characters long")

private String passportNumber;

// Getters and Setters

Let’s now define a @ControllerAdvice to handle validation errors. We do that by


overriding handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) method in
the ResponseEntityExceptionHandler.

@ControllerAdvice

@RestController

public class CustomizedResponseEntityExceptionHandler extends


ResponseEntityExceptionHandler {

@Override
protected ResponseEntity<Object>
handleMethodArgumentNotValid(MethodArgumentNotValidException ex,

HttpHeaders headers, HttpStatus status, WebRequest request) {

ErrorDetails errorDetails = new ErrorDetails(new Date(), "Validation Failed",

[Link]().toString());

return new ResponseEntity(errorDetails, HttpStatus.BAD_REQUEST);

Parameters:

MethodArgumentNotValidException ex: The exception thrown when


validation fails.

HttpHeaders headers: Contains metadata about the HTTP request/response.

HttpStatus status: The HTTP status code (in this case, 400 BAD REQUEST).

WebRequest request: Represents the current HTTP request.

To use ErrorDetails to return the error response, let’s define a ControllerAdvice as


shown below.

@ControllerAdvice

@RestController

public class CustomizedResponseEntityExceptionHandler extends


ResponseEntityExceptionHandler {
@ExceptionHandler(StudentNotFoundException)

public final ResponseEntity<ErrorDetails>


handleUserNotFoundException(StudentNotFoundException ex, WebRequest request)
{

ErrorDetails errorDetails = new ErrorDetails(new Date(), [Link](),

[Link](false));

return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);

When you execute a request with attributes not matching the constraint, you get a 404
BAD Request status back.

Request

"name": "",

"passportNumber": "A12345678"

You also get a Response Body indicating what is wrong!

"timestamp": 1512717715118,
"message": "Validation Failed",

"details": "[Link]: 1
errors\nField error in object 'student' on field 'name': rejected value []; codes
[[Link],[Link],[Link],Size]; arguments
[[Link]: codes
[[Link],name]; arguments []; default message [name],2147483647,2]; default
message [Name should have atleast 2 characters]"

[Link]
the @PathVariable annotation can be used to handle template variables in the
request URI mapping, and set them as method parameters.
A simple use case of the @PathVariable annotation would be an endpoint that
identifies an entity with a primary key:

@GetMapping("/api/employees/{id}")

@ResponseBody

public String getEmployeesById(@PathVariable String id)

return "ID: " + id;

In this example, we use the @PathVariable annotation to extract the templated part of
the URI, represented by the variable {id}.

A simple GET request to /api/employees/{id} will invoke getEmployeesById with the


extracted id value:

[Link]
----

ID: 111

Specifying the Path Variable Name

However, if the path variable name is different, we can specify it in the argument of
the @PathVariable annotation:

@GetMapping("/api/employeeswithvariable/{id}")

@ResponseBody

public String getEmployeesByIdWithVariableName(@PathVariable("id") String


employeeId)

{ return "ID: " + employeeId;

We can also define the path variable name as @PathVariable(value=”id”) instead


of PathVariable(“id”) for clarity.

Multiple Path Variables in a Single Request

Depending on the use case, we can have more than one path variable in our
request URI for a controller method, which also has multiple method parameters:

@GetMapping("/api/employees/{id}/{name}")

@ResponseBody

public String getEmployeesByIdAndName(@PathVariable String id, @PathVariable


String name) {

return "ID: " + id + ", name: " + name;

}
[Link]

----

ID: 1, name: bar

We can also handle more than one @PathVariable parameter using a method
parameter of type [Link]<String, String>:

@GetMapping("/api/employeeswithmapvariable/{id}/{name}")

@ResponseBody

public String getEmployeesByIdAndNameWithMapVariable(@PathVariable


Map<String, String>pathVarsMap) {

String id = [Link]("id");

String name = [Link]("name");

if (id != null && name != null) {

return "ID: " + id + ", name: " + name;

} else {

return "Missing Parameters";

Optional Path Variables

In Spring, method parameters annotated with @PathVariable are required by


default:

@GetMapping(value = { "/api/employeeswithrequired",
"/api/employeeswithrequired/{id}" })
@ResponseBody

public String getEmployeesByIdWithRequired(@PathVariable String id) {

return "ID: " + id;

[Link] ---- {"timestamp":"2020-07-


08T02:20:07.349+00:00","status":404,"error":"Not
Found","message":"","path":"/api/employeeswithrequired"}

[Link]
----
ID: 111

[Link] ParAmeter:

Configuration

<dependency>
<groupId>[Link]</groupId>
<artifactId>hibernate-validator</artifactId>
<version>[Link]</version>
</dependency>
We also have to enable validation for both request parameters and path
variables in our controllers by adding the @Validated annotation:
@RestController
@RequestMapping("/")
@Validated
public class RequestAndPathVariableValidationController {
// ...
}
It’s important to note that enabling parameter validation also requires
a MethodValidationPostProcessor bean. If we’re using a Spring Boot application,
then this bean is auto-configured, as we have the hibernate-validator dependency on
our classpath.

Otherwise, in a standard Spring application, we have to add this bean explicitly:

@EnableWebMvc
@Configuration
@ComponentScan("[Link]")
public class ClientWebConfigJava implements WebMvcConfigurer {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
// ...
}
By default, any error during path or request validation in Spring results in an HTTP
500 response. In this tutorial, we’ll use a custom implementation
of ControllerAdvice to handle these kinds of errors in a more readable way, returning
an HTTP 400 for any bad request.

Validating a RequestParam

Let’s consider an example where we pass a numeric weekday into a controller method
as a request parameter.
@GetMapping("/name-for-day")
public String getNameOfDayByNumberRequestParam(@RequestParam Integer
dayOfWeek) {
// ...
}
Our goal is to make sure that the value of dayOfWeek is between 1 and 7. To do so,
we’ll use the @Min and @Max annotations:
@GetMapping("/name-for-day")
public String getNameOfDayByNumberRequestParam(@RequestParam @Min(1)
@Max(7) Integer dayOfWeek) {
// ...
}
Any request that doesn’t match these conditions will return an HTTP status 400 with a
default error message.

If we call [Link] for instance, the


response message will be

[Link]: must be less than or equal to 7.


We can change the default message by adding a custom one
@Max(value = 1, message = “day number has to be less than or equal to 7”)

Validating a PathVariable

Just as with @RequestParam, we can use any annotation from


the [Link] package to validate a @PathVariable.

Let’s consider an example where we validate that a String parameter isn’t blank and
has a length of less than or equal to 10:

@GetMapping("/valid-name/{name}")
public void validStringRequestParam(@PathVariable("name") @NotBlank
@Size(max = 10) String username) {
// ...
}

Any request with a name parameter longer than 10 characters, for instance, will result
in an HTTP 400 error with a message:

[Link]:size must be between 0 and 10.

Component Purpose
DTO Classes Define structure and constraints for incoming requests.
Component Purpose
Validation Add constraints like @NotBlank, @NotNull, @Size, etc., to fields for
Annotations validation.
@ControllerAdvice Handle validation exceptions globally and return custom responses.
Use @Valid to enable validation and process requests using the validated
Controllers DTOs
RESTful Web Services

RESTful Web Services REST stands for REpresentational State Transfer. It was
developed by Roy Thomas Fielding, one of the principal authors of the web
protocol HTTP. Consequently, REST was an architectural approach designed to
make the optimum use of HTTP protocol. It uses the concepts and verbs already
present in HTTP to develop web services. This made REST incredibly easy to use
and consume, so much so that it is the go-to standard for building web services
today.

A resource can be anything, it can be accessed through a URI (Uniform Resource


Identifier). Unlike SOAP, REST does not have a standard messaging format. We
can build REST web services using many representations, including both XML and
JSON, although JSON is the more popular option. An important thing to consider is
that REST is not a standard but a style whose purpose is to constrain our
architecture to a client-server architecture and is designed to use stateless
communication protocols like HTTP.

Important Methods of HTTP


The main methods of HTTP we build web services for are:

1. GET: Reads an existing data.


2. PUT: Updates existing data.
3. POST: Creates new data.
4. DELETE: Deletes the data.

1. GET

The default request method for HTTP. We don’t have any request body with this
method, but we can define multiple request parameters or path variables in the URL.
This method is used for getting obtaining some resources. Depending on the
presence of an ID parameter, either we can fetch a specific resource or fetch a
collection of resources in the absence of the parameter. Sample GET request in
Spring Boot Controller:
@GetMapping("/user/{userId}")
public ResponseEntity<Object> getUser(@PathVariable int userId) {
UserEntity user = [Link](userId);
return new ResponseEntity<>(user, [Link]);
}

Example of GET operation to perform in an application:

 GET/employees: This will retrieve all employee details.

2. POST

The POST method of HTTP is used to create a resource. We have a request body in
this method and can also define multiple request parameters or path variables in the
URL. Sample POST request in Spring Boot Controller:

@PostMapping(value = "/user")
public ResponseEntity<Object> addUser(@RequestBody UserEntity user) {
[Link](user);
return new ResponseEntity<>("User is created successfully",
[Link]);
}

Example of POST operation to perform in an application:

 POST/employees: This will create an employee.

3. PUT

The PUT method of HTTP is used to update an existing resource. We have a request
body in this method and can also define multiple request parameters or path
variables in the URL. Sample PUT request in Spring Boot Controller:

@PutMapping("/user/{userId}")
public ResponseEntity<Object> getUser(@RequestBody UserEntity user) {
[Link](user);
return new ResponseEntity<>("User is updated successfully", [Link]);
}

Example of PUT operation to perform in an application:

 PUT/employees/{id}: This will update an existing employee’s details.

4. DELETE

The DELETE method of HTTP is used to remove a resource. We don’t have a


request body in this method but can define multiple request parameters or path
variables in the URL. We can delete multiple or single records, usually based on
whether we have an ID parameter or not. We can delete multiple or single records,
usually based on whether we have an ID parameter or not. Sample DELETE request
in Spring Boot Controller:

@DeleteMapping(value = "/user")
public ResponseEntity<Object> addUser(@PathVariable int userId) {
[Link](userId);
return new ResponseEntity<>("User is deleted successfully", [Link]);
}

Example of DELETE operation to perform in an application:

 DELETE/employees: This will delete all employees.


REST web services use the Status-Line part of an HTTP response message to
inform clients of their request’s ultimate result.

HTTP Standard Status Codes


The status codes defined in HTTP are the following:

 200: Success
 201: Created
 401: Unauthorized
 404: Resource Not Found
 500: Server Error
Principles of RESTful web services

The following are the main principles rest services follow, which makes them fast,
lightweight, and secure are:

 Resource Identification through URI- A RESTful web service provides an


independent URI/ global ID for every resource.
 Uniform Interface- Resources are manipulated using a fixed set of four
create, read, update, delete operations: PUT, GET, POST, and DELETE.
 Self-descriptive messages- Resources and representations are decoupled in a
RESTful web service. This allows us to represent the payload in various formats
such as HTML, XML, plain text, PDF, JPEG, JSON, and others based on our use
case.
 Stateful Interaction through hyperlinks- Every interaction with a resource is
stateless; that is, request messages are self-contained.

Advantages of RESTful web services

Some of the primary advantages of using RESTful web services are,

 Easy to Build: REST APIs are simpler to build than a corresponding SOAP
API. Hence, REST is the better choice if we want to develop APIs quickly.
 Independent: Since the client and server are decoupled in RESTful web
services, it allows for independent development across projects.
 Scalability: Stateless communication and a replicated repository provide a
high level of scalability. Compared to SOAP, scaling up an existing website is
easier with the REST web services.
 Layered System: REST web services have their application divided into
multiple layers forming a hierarchy. It makes the application both modular and
scalable.
Consuming REST Services in Spring Boot
Spring Boot provides several robust options for consuming RESTful web services. In
this blog post, we will explore three primary methods: RestTemplate, WebClient, and
Feign Client. Each approach offers unique features and benefits suited for different
use cases.

1. RestTemplate
Description: RestTemplate is a synchronous client for performing HTTP requests. It
is simple to use and ideal for applications where synchronous calls are sufficient.
Synchronous client:
This means that the client waits for a response from the server before proceeding with
the next action.

Setup and Usage:

Add Dependency: To use RestTemplate, add the following dependency to your


[Link]:

<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Configuration: Configure RestTemplate as a bean:

@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return [Link]();
}
}
Service Implementation: Use RestTemplate in your service class:

@Service
public class RestTemplateService {
private final RestTemplate restTemplate;

public RestTemplateService(RestTemplate restTemplate) {


[Link] = restTemplate;
}

public String getSomethingFromApi(String url) {


return [Link](url, [Link]);
}
}
2. WebClient
Description: WebClient is a non-blocking, reactive client for performing HTTP
requests. It supports both synchronous and asynchronous operations, making it
ideal for reactive applications.

Setup and Usage:

Add Dependency: To use WebClient, add the following dependency to your


[Link]:

<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

Configuration: Configure WebClient as a bean:

@Configuration
public class WebClientConfig {
@Bean
public [Link] webClientBuilder() {
return [Link]();
}
}
Service Implementation: Use WebClient in your service class:

@Service
public class WebClientService {
private final WebClient webClient;

public WebClientService([Link] webClientBuilder) {


[Link] = [Link]();
}

public Mono<String> getSomethingFromApi(String url) {


return [Link]()
.uri(url)
.retrieve()
.bodyToMono([Link]);
}
}
3. Feign Client
Description: Feign is a declarative web service client that simplifies the process of
writing web service clients by providing a simple, annotation-based API.

Setup and Usage:

Add Dependency: To use Feign, add the following dependency to your [Link]:

<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
Enable Feign Clients: Enable Feign clients in your main application class:

@SpringBootApplication
@EnableFeignClients
public class Application {
public static void main(String[] args) {
[Link]([Link], args);
}
}
Define Feign Client: Define the Feign client interface:

@FeignClient(name = "apiClient", url = "[Link]


public interface ApiClient {
@GetMapping("/endpoint")
String getSomething();
}
Service Implementation: Use the Feign client in your service class:

@Service
public class FeignClientService {
private final ApiClient apiClient;

public FeignClientService(ApiClient apiClient) {


[Link] = apiClient;
}

public String getSomethingFromApi() {


return [Link]();
}
}
Spring Boot - Complete Guide to Validations for REST API’s
Validations:
Validations in Spring Boot are an integral part of building robust
and secure REST APIs. They help ensure that incoming requests contain
valid and well-formed data before processing them further

Hibernate Validator
[Link] Validation Dependency
[Link] Validation Constraints in DTO.
[Link] Request Data in Controller
[Link] Validation Error Responses

Dependencies
To use the validation framework in our application we need to add following
dependencies to our project.

<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Bean Validation
Bean Validation works by adding constraint annotations on the fields of the class to
be validated. Commonly used annotations are defined in [Link]
package.

@NotNull: Used when a field must not be null.


@NotEmpty: Used when a list field must not empty.
@NotBlank: Used when a string field must not be the empty string (i.e. it must have
at least one character).
@Min and @Max: Used when a numerical field is only valid when it’s value is
above or below a certain value.
@Pattern: Used when a string field is only valid when it matches a certain regular
expression.
@Email: Used when a string field must be a valid email address.

An example of class with annotations :

1 public class StudentDto {


2
3 @NotBlank(message = "Should not be null or empty.")
4 private String firstName;
5
6 @Email(message = "Not valid.")
7 private String email;
8
9 @Size(min = 4, max = 10, message = "Should be min 4 character and max
10 10 character in length.")
11 private String password;}

Validation of Inputs to a REST Controller:


There are 3 things which are to be validated for a incoming REST request:

[Link] Body
[Link] Variables
[Link] Parameters
[Link]:

Implementing Validations on the Bean

Before we add validations, we need to add a dependency.

<dependency>

<groupId>[Link]</groupId>

<artifactId>spring-boot-starter-validation</artifactId>

</dependency>

Let’s add a few validations to the Student bean. We are using @Size to specify the
minimum length and also a message when a validation error occurs.

public ResponseEntity<Object> createStudent(@Valid @RequestBody Student


student) {

@Entity

public class Student {

@Id

@GeneratedValue

private Long id;

@NotNull

@Size(min=2, message="Name should have atleast 2 characters")

private String name;


@NotNull

@Size(min=7, message="Passport should have atleast 2 characters")

private String passportNumber;

 The @Valid annotation ensures that the Student object is validated against the
constraints specified in the Student class before the controller's logic is executed.

 If validation fails (e.g., a field does not meet the constraints), Spring will throw
a MethodArgumentNotValidException. You can handle this exception globally to
return custom error messages

@Entity Annotation

This marks the Student class as a JPA Entity, meaning it maps to a table in a
database.

 By default, the table name corresponds to the class name (Student), but you
can customize it using the @Table annotation.

 @Id: Specifies that the id field is the primary key of the Student entity.

 @GeneratedValue: Automatically generates unique values for the id field. The


default generation strategy is used unless explicitly specified.

 Ensures that the name and passportNumber fields cannot be null.

 If a client sends a JSON object without the name or passportNumber fields,


validation will fail.

 @Size: Validates the length of a String, Collection, Map, or Array.

min=2: The name field must have at least 2 characters.

min=7: The passportNumber field must have at least 7 characters.

 message: The custom message returned to the client when validation fails.

Enabling Validation on the Resource


The @GeneratedValue annotation in Java's JPA (Java Persistence API)
is used to specify how the primary key (annotated with @Id) of an
entity should be automatically generated

Simple. Add @Valid in addition to @RequestBody.

public ResponseEntity<Object> createStudent(@Valid @RequestBody Student


student) {

It automatically converts JSON or XML data from the request body into a Java object
When you execute a request with attributes not matching the constraint, you get a 404
BAD Request status back.
Request

"name": "",

"passportNumber": "A12345678"

}
Customizing Validation Response

Let’s define a simple error response bean.

public class Student {

@NotNull(message = "Name is mandatory")

@Size(min = 2, message = "Name must be at least 2 characters long")

private String name;

@NotNull(message = "Passport number is required")

@Size(min = 7, message = "Passport number must be at least 7 characters long")

private String passportNumber;

// Getters and Setters

Let’s now define a @ControllerAdvice to handle validation errors. We do that by


overriding handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) method in
the ResponseEntityExceptionHandler.

@ControllerAdvice

@RestController

public class CustomizedResponseEntityExceptionHandler extends


ResponseEntityExceptionHandler {
@Override

protected ResponseEntity<Object>
handleMethodArgumentNotValid(MethodArgumentNotValidException ex,

HttpHeaders headers, HttpStatus status, WebRequest request) {

ErrorDetails errorDetails = new ErrorDetails(new Date(), "Validation Failed",

[Link]().toString());

return new ResponseEntity(errorDetails, HttpStatus.BAD_REQUEST);

Parameters:

MethodArgumentNotValidException ex: The exception thrown when


validation fails.

HttpHeaders headers: Contains metadata about the HTTP request/response.

HttpStatus status: The HTTP status code (in this case, 400 BAD REQUEST).

WebRequest request: Represents the current HTTP request.

To use ErrorDetails to return the error response, let’s define a ControllerAdvice as


shown below.

@ControllerAdvice

@RestController
public class CustomizedResponseEntityExceptionHandler extends
ResponseEntityExceptionHandler {

@ExceptionHandler(StudentNotFoundException)

public final ResponseEntity<ErrorDetails>


handleUserNotFoundException(StudentNotFoundException ex, WebRequest request)
{

ErrorDetails errorDetails = new ErrorDetails(new Date(), [Link](),

[Link](false));

return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);

When you execute a request with attributes not matching the constraint, you get a 404
BAD Request status back.

Request

"name": "",

"passportNumber": "A12345678"

You also get a Response Body indicating what is wrong!

{
"timestamp": 1512717715118,

"message": "Validation Failed",

"details": "[Link]: 1
errors\nField error in object 'student' on field 'name': rejected value []; codes
[[Link],[Link],[Link],Size]; arguments
[[Link]: codes
[[Link],name]; arguments []; default message [name],2147483647,2]; default
message [Name should have atleast 2 characters]"

[Link]
the @PathVariable annotation can be used to handle template variables in the
request URI mapping, and set them as method parameters.
A simple use case of the @PathVariable annotation would be an endpoint that
identifies an entity with a primary key:

@GetMapping("/api/employees/{id}")

@ResponseBody

public String getEmployeesById(@PathVariable String id)

return "ID: " + id;

In this example, we use the @PathVariable annotation to extract the templated part of
the URI, represented by the variable {id}.

A simple GET request to /api/employees/{id} will invoke getEmployeesById with the


extracted id value:
[Link]

----

ID: 111

Specifying the Path Variable Name

However, if the path variable name is different, we can specify it in the argument of
the @PathVariable annotation:

@GetMapping("/api/employeeswithvariable/{id}")

@ResponseBody

public String getEmployeesByIdWithVariableName(@PathVariable("id") String


employeeId)

{ return "ID: " + employeeId;

We can also define the path variable name as @PathVariable(value=”id”) instead


of PathVariable(“id”) for clarity.

Multiple Path Variables in a Single Request

Depending on the use case, we can have more than one path variable in our
request URI for a controller method, which also has multiple method parameters:

@GetMapping("/api/employees/{id}/{name}")

@ResponseBody

public String getEmployeesByIdAndName(@PathVariable String id, @PathVariable


String name) {
return "ID: " + id + ", name: " + name;

[Link]

----

ID: 1, name: bar

We can also handle more than one @PathVariable parameter using a method
parameter of type [Link]<String, String>:

@GetMapping("/api/employeeswithmapvariable/{id}/{name}")

@ResponseBody

public String getEmployeesByIdAndNameWithMapVariable(@PathVariable


Map<String, String>pathVarsMap) {

String id = [Link]("id");

String name = [Link]("name");

if (id != null && name != null) {

return "ID: " + id + ", name: " + name;

} else {

return "Missing Parameters";

Optional Path Variables


In Spring, method parameters annotated with @PathVariable are required by
default:

@GetMapping(value = { "/api/employeeswithrequired",
"/api/employeeswithrequired/{id}" })

@ResponseBody

public String getEmployeesByIdWithRequired(@PathVariable String id) {

return "ID: " + id;

[Link] ---- {"timestamp":"2020-07-


08T02:20:07.349+00:00","status":404,"error":"Not
Found","message":"","path":"/api/employeeswithrequired"}

[Link]
----
ID: 111

3. Query Parameter:

A query parameter is a key–value pair that you append to the end of


a URL to pass information to the server. They are typically used in
REST APIs and web applications to filter, sort, or customize the
response

Configuration

<dependency>
<groupId>[Link]</groupId>
<artifactId>hibernate-validator</artifactId>
<version>[Link]</version>
</dependency>
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;

@RestController
@RequestMapping("/")
@Validated
public class RequestAndPathVariableValidationController {

// ✅RequestParam validation
@GetMapping("/name-for-day")
public String getNameOfDayByNumberRequestParam(
@RequestParam
@Min(value = 1, message = "Day number must be >= 1")
@Max(value = 7, message = "Day number must be <= 7") Integer
dayOfWeek) {

// Example mapping logic


String[]days =
{"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sund
ay"};
return days[dayOfWeek - 1];
}

// ✅PathVariable validation
@GetMapping("/valid-name/{name}")
public String validStringRequestParam(
@PathVariable("name")
@NotBlank(message = "Name must not be blank")
@Size(max = 10, message = "Name must be at most 10 characters")
String username) {
return "Validated username: " + username;
}
}

RequestParam Validation (/name-for-day)


Valid request
GET [Link]

OUTPUT:Wednesday

GET [Link]
JSON RESPONSE:
{
"[Link]": "Day number must be
<= 7"}

PathVariable Validation (/valid-name/{name})

GET [Link]

Validated username: John

INVALID REQUEST:
GET [Link]

{
"[Link]": "Name must not be blank"}
Validate Create Post and Update Post REST API Request:

1. Define the DTOs with Validation Annotations


public class PostRequest {

@NotBlank(message = "Title is mandatory")


@Size(max = 100, message = "Title must be less than 100
characters")
private String title;

@NotBlank(message = "Content cannot be empty")


@Size(max = 5000, message = "Content must be less than 5000
characters")
private String content;

// getters and setters}

2. Controller Endpoints with Validation

import [Link].*;
import [Link];

@RestController
@RequestMapping("/posts")
public class PostController {

// CREATE POST
@PostMapping
public String createPost(@Valid @RequestBody PostRequest
postRequest) {
// service call
return "Post created successfully!";
}

// UPDATE POST
@PutMapping("/{id}")
public String updatePost(@PathVariable Long id,
@Valid @RequestBody PostRequest
postRequest) {
// service call
return "Post updated successfully!";
}
}
3. Global Exception Handling for Validation Errors
import [Link];
import [Link];
import [Link];
import [Link];

import [Link];
import [Link];

@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler([Link])
public ResponseEntity<Map<String, String>>
handleValidationExceptions(
MethodArgumentNotValidException ex) {

Map<String, String> errors = new HashMap<>();


[Link]().getFieldErrors().forEach(error ->
[Link]([Link](), [Link]())
);

return [Link]().body(errors);
}
}
4. Example Requests & Responses

Valid Create Request


POST /posts
Content-Type: application/json

{
"title": "Spring Boot Validation",
"content": "This is a valid post content."
}
Response:
"Post created successfully!"
Invalid Request:
POST /posts
Content-Type: application/json

{
"title": "",
"content": ""
}
Response:
{
"title": "Title is mandatory",
"content": "Content cannot be empty"
}

Validate Create Comment and Update Comment REST API


[Link] the Comment DTO with Validation

import [Link];
import [Link];

public class CommentDTO {

private Long id; // used for update

@NotBlank(message = "Comment text must not be blank")


@Size(min = 5, max = 500, message = "Comment must be between 5
and 500 characters")
private String text;
@NotBlank(message = "Author name is required")
private String author;

// getters and setters


}
2. REST Controller Endpoints
import [Link];
import [Link];
import [Link].*;

@RestController
@RequestMapping("/api/comments")
public class CommentController {

private final CommentService commentService;

public CommentController(CommentService commentService) {


[Link] = commentService;
}
// CREATE COMMENT
@PostMapping
public ResponseEntity<CommentDTO> createComment(@Validated
@RequestBody CommentDTO commentDTO) {
CommentDTO saved = [Link](commentDTO);
return [Link](saved);
}

// UPDATE COMMENT
@PutMapping("/{id}")
public ResponseEntity<CommentDTO> updateComment(
@PathVariable Long id,
@Validated @RequestBody CommentDTO commentDTO) {
[Link](id);
CommentDTO updated = [Link](commentDTO);
return [Link](updated);
}
}

3. Service Layer (Business Logic)


import [Link];

@Service
public class CommentService {

public CommentDTO createComment(CommentDTO dto) {


// persist to DB (mocked here)
[Link](1L); // assume generated ID
return dto;
}

public CommentDTO updateComment(CommentDTO dto) {


// fetch existing, update fields, save
return dto; // returning updated object
}
}
4. Validation Error Handling:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

import [Link];
import [Link];

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler([Link])
public ResponseEntity<Map<String, String>>
handleValidationErrors(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
[Link]().getFieldErrors().forEach(error ->
[Link]([Link](), [Link]())
);
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}
}
Create Comment (Valid):

POST /api/comments
Content-Type: application/json

{
"text": "This is a valid comment with enough length.",
"author": "Seetha"
}
Response:
{
"id": 1,
"text": "This is a valid comment with enough length.",
"author": "Seetha"
}

Create Comment (Invalid):

POST /api/comments
Content-Type: application/json

{
"text": "Hi",
"author": ""
}
Response
{
"text": "Comment must be between 5 and 500 characters",
"author": "Author name is required"
}

Update Comment

PUT /api/comments/1
Content-Type: application/json

{
"text": "Updated comment text with proper length.",
"author": "Seetha"
}
Response:
{
"id": 1,
"text": "Updated comment text with proper length.",
"author": "Seetha"
}

Component Purpose
Define structure and constraints for incoming
DTO Classes
requests.
Validation Add constraints like @NotBlank, @NotNull, @Size,
Annotations etc., to fields for validation.
Handle validation exceptions globally and return
@ControllerAdvice
custom responses.
Use @Valid to enable validation and process
Controllers
requests using the validated DTOs

You might also like