0% found this document useful (0 votes)
33 views157 pages

Spring Framework

The Spring Framework is a comprehensive ecosystem for building Java applications, featuring components like Core, Boot, Data, Security, and Integration. It contrasts with Jakarta EE by offering a more flexible and non-intrusive approach to enterprise application development. Key concepts include Inversion of Control (IoC) and Dependency Injection (DI), which promote decoupling and easier testing of components.

Uploaded by

ramlalac68
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)
33 views157 pages

Spring Framework

The Spring Framework is a comprehensive ecosystem for building Java applications, featuring components like Core, Boot, Data, Security, and Integration. It contrasts with Jakarta EE by offering a more flexible and non-intrusive approach to enterprise application development. Key concepts include Inversion of Control (IoC) and Dependency Injection (DI), which promote decoupling and easier testing of components.

Uploaded by

ramlalac68
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

Spring

Framework
What is Spring? (The Ecosystem)
Concept:
Spring is not just a single "Framework"; it is a massive Ecosystem for building
Java applications.

o Core: The engine (IoC, DI).


o Boot: The fast setup (Auto-configuration).
o Data: The DB access (JPA, MongoDB).
o Security: The bouncer (Auth/Authz).
o Integration: Tools for enterprise integration (Spring Integration, JMS, etc.).

The "Why": Before Spring (in the EJB era), Java Enterprise development was
heavy, complex, and required massive XML files. Spring was created to be
Lightweight and Non-Invasive (your code doesn't need to extend Spring
classes to work).

Jakarta EE vs. Spring (The Battle of


Standards)
Spring and Jakarta EE (formerly Java EE) are both used to build enterprise-level
applications. While Jakarta EE provides a standardized, specification-based
approach, Spring is more flexible and non-intrusive. Spring allows easier
integration with other frameworks and technologies, which makes it a go-to
choice for modern, scalable applications.
Feature Jakarta EE (formerly J2EE) Spring Framework

It is a Specification (A set of It is an Implementation (A working


Nature
Interfaces/Rules). Framework).

"Pick and choose." Modular &


Philosophy "One size fits all." Heavyweight.
Lightweight.

Uses those standards! Spring uses the


Defines standards like JPA, Servlet,
Relation Jakarta Servlet spec for Web and
JMS.
Jakarta Persistence for Data.

Spring is the "Meal Kit" that prepares


Real World Jakarta EE is the "Raw Ingredients".
them for you.
M.T.M. Aathif | Spring Boot | 2025
Inversion of Control (IoC) & Dependency
Injection (DI)
This is the most important concept in Spring.
IoC Concept: Traditionally, your program controls the flow. With IoC, you
delegate that control to a framework (like Spring). The framework is
responsible for creating and managing objects
o The Principle: "The Hollywood Principle" -> Don't call us, we'll call you.
o Meaning: Instead of your class asking for resources, the framework gives
them to the class.
Dependency Injection (DI) is the design pattern used to implement IoC.
Dependency is an object that another object requires, and Injection refers to
passing that dependency to the class rather than having the class create it
itself.

The Implementation: Dependency Injection (DI)


DI is the specific design pattern used to achieve IoC.
o Dependency: An object that another object needs to function (e.g., A Car
needs an Engine).
o Injection: Passing the dependency in (rather than creating it inside).

Real-World Analogy: The Pizza Shop


Without IoC (The "Old" Way): You want a Pizza. You have to:
1. Grow the wheat.
2. Make the sauce.
3. Bake the pizza. Result: You are tightly coupled to the ingredients. If the cow
gets sick, you don't eat.
With IoC (The "Spring" Way): You want a Pizza. You call the Pizza Shop (The IoC
Container).
1. You say: "I need a Pizza."
2. The Shop (Container) has already prepared the dough, cheese, and sauce
(Beans).
3. The Shop Injects the pizza into your hand. Result: You focus on eating
(Business Logic), not cooking (Object Creation).

M.T.M. Aathif | Spring Boot | 2025


Demo: IoC & DI in Action

The "Tightly Coupled" Way (Bad)

The "Spring/DI" Way (Good)

Advantages of this approach:


1. Decoupling: Car doesn't care if it's a V8Engine or ElectricEngine. It just
works.
2. Testing: In a unit test, you can easily pass a MockEngine into the
constructor. You can't do that if new V8Engine() is hidden inside the class.

M.T.M. Aathif | Spring Boot | 2025


The Spring IoC Container

The Container is the runtime system that creates, wires, and manages your
beans (objects).
Two Types of Containers:
1. BeanFactory (The Heart): A lightweight container that loads beans lazily,
i.e., only when requested. Ideal for memory-constrained devices (IoT).
2. ApplicationContext (The Body): The more advanced container that eagerly
loads beans at startup and provides additional features like event
publication and AOP. In Spring Boot applications, ApplicationContext is the
container used 99% of the time.

Spring Beans
A Bean is simply a Java Object that is managed by the Spring IoC Container.
How to make a Bean?
To create a bean, use the @Component (or @Service, @Repository, etc.)
annotation, or define it inside a @Configuration class using the @Bean
annotation.
Lifecycle:
Spring controls the lifecycle of a bean, including when it's initialized and
destroyed, using the @PostConstruct and @PreDestroy annotations.

M.T.M. Aathif | Spring Boot | 2025


Spring Expression Language (SpEL)
SpEL is a powerful language used to query and manipulate the object graph at
runtime. You use it inside annotations.
Syntax: #{ expression }

Examples
1. Injecting System Properties:

2. Mathematical Operations:

3. Referencing other Beans:

M.T.M. Aathif | Spring Boot | 2025


MAVEN
Maven Introduction
Concept:
Maven is not just a tool to download .jar files; it’s a Project
Management and Build Automation tool.
Maven is responsible for:
❑ Builds: Compiling code, running tests, packaging (JAR/WAR).
❑ Dependencies: Automatically downloading libraries (Spring
Boot, Database drivers).
❑ Best Practices: Enforcing a standard directory structure
(src/main/java, src/test/java)

Real-World Analogy:
Maven acts as the General Contractor on a construction site. You provide the
blueprints ([Link]), and Maven hires workers (plugins), orders materials
(dependencies), and manages the schedule (lifecycle).
You (Developer): Give the blueprints ([Link]).
Maven: Hires the workers (Plugins), orders the materials (Dependencies),
and manages the schedule (Lifecycle). You don't tell a worker how to
hammer a nail; you just tell the Contractor "Build the wall," and they handle
the details.

M.T.M. Aathif | Spring Boot | 2025


How Maven Works
Maven uses a Repository System to find libraries. It doesn't store libraries
inside your project folder (unlike old-school copy-pasting).
The 3-Tier Flow:
1. Local Repository: A folder on your computer (.m2/repository). Maven
checks here first.
2. Central Repository: The massive global library on the internet. If a jar
isn't local, Maven downloads it from here.
3. Remote/Internal Repository: (Enterprise only) A private server (like
Nexus/Artifactory) where your company hosts its own private libraries.
When you add dependencies (e.g., spring-boot-starter-web), Maven first
checks the local repository. If the required JAR isn't found, Maven will
download it from the Central Repository

Example:
When you add spring-boot-starter-web:
Maven looks in your .m2 folder. Not there?
It connects to [Link].
Downloads the JAR + Transitive Dependencies (libraries that Spring Web
needs, like Tomcat and Jackson).

M.T.M. Aathif | Spring Boot | 2025


The [Link] & Effective POM
The [Link] file is the brain of your Maven project. It contains key elements
like:
Key Elements (G.A.V.):
Every Maven project is identified by three coordinates:
❑ GroupId: Who created it? Identifies the project’s group (Reverse domain:
[Link])
❑ ArtifactId: What is it? The name of the project (Project name: my-
ecommerce-app)
❑ Version: Which iteration? The version of the project (1.0.0-SNAPSHOT)

The "Effective POM" (Advanced Topic)


o Your [Link] might look small (20 lines), but the Effective POM is huge
(hundreds of lines).
o Why? Spring Boot uses a concept called Parent Inheritance. Your project
extends spring-boot-starter-parent.
o What it does: The parent defines default versions for plugins, Java versions,
and dependencies so you don't have to.
o How to see it: Run mvn help:effective-pom in the terminal to see the "real"
full configuration.

M.T.M. Aathif | Spring Boot | 2025


Dependency Management
& Scopes
Adding a dependency is easy, but understanding Scopes is what
distinguishes a Junior from a Senior dev.
Common Scopes:
❑ Compile (Default): Available everywhere (Main code + Tests). Ends up
in the final JAR.
Example: Spring Boot Starter Web.
❑ Test: Only available in src/test. NOT in the final JAR.
Example: JUnit, Mockito. (You don't want testing code in your production
app!).
❑ Provided: You need it to compile, but the server (like an external
Tomcat) will provide it at runtime.
Example: Lombok (It generates code during compile, but isn't needed
effectively at runtime in the same way).
❑ Runtime: Not needed for compilation, but needed to run.
Example: MySQL Driver (You code against JDBC interfaces, not the driver
implementation directly).

M.T.M. Aathif | Spring Boot | 2025


The Build Lifecycle
You cannot understand Maven without the Lifecycle. It is a
sequence of phases. Running one phase runs all previous phases.

clean: Deletes the target folder (removes old build artifacts).

validate: Checks if project is correct.

compile: Compiles source code (.java -> .class).

test: Runs Unit Tests (JUnit). If tests fail, the build stops!

package: Bundles code into a JAR or WAR.

install: Copies the JAR to your Local Repository (so other local
projects can use it).

deploy: Uploads the JAR to a Remote Repository


(Nexus/Artifactory) for others on your team.

What is the difference between package and install?


o package creates the file in your project folder (target/).
o install does package AND copies it to your global .m2 folder.

M.T.M. Aathif | Spring Boot | 2025


Maven Archetypes
Concept:
An Archetype is a template. Instead of creating folder structures manually,
you use an archetype to generate a skeleton project.

maven-archetype-quickstart creates a basic Java app. However, in the


Spring Boot world, we rarely use raw Maven archetypes anymore. We use the
Spring Initializr, which acts like a super-powered modern archetype
generator.

The Maven Wrapper (mvnw)


You will see a file called mvnw in every Spring Boot project.
❑ The Problem: You have Maven 3.8 installed. Your colleague has Maven
3.6. The build might behave differently.
❑ The Solution: The Wrapper. It is a script that downloads a specific version
of Maven just for that project.
❑ Best Practice: Always run ./mvnw clean install instead of mvn clean
install in CI/CD pipelines to ensure consistency.

M.T.M. Aathif | Spring Boot | 2025


Creating & Managing
Spring Beans
Two Ways to Create Beans

(Topic: @Bean vs @Component)


This is the most fundamental choice you make in Spring.
Approach A: The @Component Way (Stereotype Annotations)
Concept:
You own the source code. You add an annotation to your class, and Spring
finds it automatically (Component Scanning).
▪ Use Case: Your own Services, Controllers, and Repositories.

Stereotype Annotations (The "Specialized" Components): While @Component


is the generic annotation, Spring provides specific versions to indicate the role
of the class:
1. @Service: Holds business logic.
2. @Repository: Holds database logic (and translates SQL exceptions).
3. @Controller: Handles web requests.
Real-World Example:

M.T.M. Aathif | Spring Boot | 2025


(Topic: @Bean vs @Component)
This is the most fundamental choice you make in Spring.
Approach B: @Bean Way
Concept:
You don't own the source code (it's a 3rd party library), or you need custom
configuration logic. You write a method inside a @Configuration class that
returns the object.
▪ Use Case: Configuring Gson, Database Client, or AWS SDK.
Real-World Example: You can't add @Component to the Gson class source
code (it belongs to Google).

M.T.M. Aathif | Spring Boot | 2025


Comparison between @Bean Vs
@Component

Feature @Component @Bean

On a Method level (inside


Where? On the Class level.
@Configuration).

Automatic (Spring scans and Manual (You write the new


Control
news it). keyword).

Use You are using a 3rd party


You wrote the class.
When? library.

M.T.M. Aathif | Spring Boot | 2025


Handling Bean Conflicts

(Topic: NoUniqueBeanDefinitionException & @Primary)


The Problem:
What if you have an interface SmartLight and two implementations:
XiaomiLight and PhilipsHueLight? If you try to inject SmartLight, Spring panics
because it doesn't know which one to give you. This throws
NoUniqueBeanDefinitionException.

Solution 1: @Primary - Use @Primary to designate the default bean


Mark one implementation as the default.

Solution 2: Custom Naming (@Qualifier) - Use @Qualifier to specify which


bean to inject by name.
Give the beans specific names and ask for them by name.
Defining the Name:

Injecting by Name:

M.T.M. Aathif | Spring Boot | 2025


The Bean Lifecycle
(Topic: @PostConstruct & @PreDestroy)
Spring manages the life of a bean. You can hook into the startup and shutdown
phases.
@PostConstruct (The "Startup" Hook)
Runs after the constructor is called and after dependencies are injected.
Use Case: Connecting to a smart device, populating a cache, checking API
keys, establishing database connections.

@PreDestroy (The "Shutdown" Hook)


Runs just before the application stops or the bean is removed from the
container.
Use Case: Closing open files, disconnecting database connections, saving final
state, releasing resources.

M.T.M. Aathif | Spring Boot | 2025


Legacy & Advanced Configuration

(Topic: XML, Programmatic, Why Frameworks?)


Creating Beans using XML (The "Old School" Way)
Before annotations (Spring 2.0 era), everything was XML. You might still see
this in legacy banking apps. [Link]:

▪ Why avoid it now? No type safety. If you misspell the class name in XML,
you won't know until runtime crash.

Programmatic Registration (registerBean)


Spring 5 introduced a functional way to register beans, often used in Kotlin or
high-performance serverless apps where you want to avoid scanning latency.

Why should we use Frameworks? (The "Big Picture")


1. Inversion of Control: Decouples your code. You can swap MySqlDatabase
for OracleDatabase without rewriting your Service layer.
2. Boilerplate Reduction: Writing a JDBC connection takes 50 lines of Java.
Spring Data JPA takes 0 lines.
3. Transaction Management: Writing try-catch-rollback blocks is error-prone.
Spring handles it with one annotation (@Transactional).
4. Security & Robustness: Frameworks have been tested by millions of
developers. Your custom solution hasn't.

M.T.M. Aathif | Spring Boot | 2025


Mastering Bean
Scopes
Introduction to Bean Scopes

(Topic: The Menu of Options)


A "Scope" defines two things: How many instances of a bean are created, and
how long they live.
Spring supports 6 scopes, but you will use the first two 90% of the time.

Scope Description Context


Singleton (Default) One instance per Spring Container. Core Spring

Prototype A new instance every time it is requested. Core Spring

Request One instance per HTTP Request. Web Only

Session One instance per HTTP User Session. Web Only

One instance per ServletContext (Global Web


Application Web Only
App).

WebSocket One instance per WebSocket session. Web Only

M.T.M. Aathif | Spring Boot | 2025


Deep Dive: Singleton Scope
(Topic: The Default Behavior)
Concept: By default, every bean in Spring is a Singleton. If you define a
ProductService, Spring creates ONE instance of it at startup and caches it.
Every time you inject ProductService into a Controller or another Service, you
get that exact same shared instance.
Real-World Analogy: The Office Printer
▪ Imagine an office with 50 employees (Threads).
▪ There is one shared Printer (Singleton Bean).
▪ When Employee A sends a document, and Employee B sends a document,
they both use the same physical machine.
Use Cases for Singleton
▪ Stateless Services: Classes that just hold logic/methods (Service Layer).
▪ Data Repositories: DB connection managers.
▪ Configuration Classes: Global settings.

The Danger Zone: Race Conditions


(Topic: Thread Safety)
Race Conditions: If a singleton bean is stateful, meaning it holds data, multiple
threads accessing the same bean can cause data corruption. Always ensure
Singleton beans are stateless.
The Buggy Code (Stateful Singleton):

❖ Scenario: User A and User B call bookTicket() at the exact same


millisecond. Both read count as 0. Both increment to 1. Total tickets booked
should be 2, but the system says 1. Data is corrupted.
The Fix: Do not store state in the Service. Pass state through method
arguments or use the Database to hold the count.
M.T.M. Aathif | Spring Boot | 2025
Eager vs. Lazy Instantiation
(Topic: Controlling Startup Time)
Eager Initialization (Default)
Spring creates all Singleton beans immediately when the application starts.
▪ Pros: Fails fast. If you have a missing config or DB connection error, the app
crashes immediately (good for Ops).
▪ Cons: Slow startup time if you have thousands of beans.

Lazy Initialization (@Lazy)


Spring creates the bean only when it is first requested (injected).
▪ Pros: Faster startup. Saves memory if the bean is rarely used.
▪ Cons: Errors are hidden until the user actually triggers that feature.

Code Demo: Eager vs. Lazy

Output (Eager - Default):

Output (Lazy - with @Lazy):

M.T.M. Aathif | Spring Boot | 2025


Deep Dive: Prototype Scope
(Topic: New Instance Per Request)
Concept
When a bean is defined as Prototype, Spring gives you a brand new new
Object() every time you ask for it. Spring does not manage the lifecycle after
creation (it hands it to you and forgets it; no @PreDestroy support!).
Real-World Analogy: The Coffee Shop
▪ When you order a latte, the barista gives you a new cup.
▪ They don't give you the same cup the previous customer used (that would
be gross/Singleton).
▪ You own the cup. When you are done, you throw it away (Garbage
Collection).
Use Cases for Prototype
▪ Stateful Beans: Objects that need to hold user-specific data (e.g., a
Shopping Cart logic, though usually Session scope is better).
▪ Non-Thread-Safe Objects: Wrappers around SimpleDateFormat or other
legacy non-thread-safe classes.
Configuration:

M.T.M. Aathif | Spring Boot | 2025


Singleton vs. Prototype (Summary)

Feature Singleton Prototype

Creation Created once per container. Created every time requested.

State Must be Stateless (Thread-safe). Can be Stateful.

Creation only (No Destroy


Lifecycle Fully managed (Init + Destroy).
callback).

High consumption (Many


Memory Efficient (1 object).
objects).

Usage 99% of beans (Services, Repos). Rare (Specific stateful needs).

The "Prototype in Singleton" Problem


(Topic: Important Advanced Concept)
This is a classic interview question. Scenario: You inject a Prototype bean
(Coffee Cup) into a Singleton bean (Barista).

The Trap: Spring creates the Singleton Barista once at startup. To do that, it
injects one CoffeeCup. Even though CoffeeCup is a Prototype, the Barista
holds onto that same cup forever. Every customer gets the exact same cup
instance! The Prototype scope is effectively "killed" by the enclosing Singleton.
The Fix: Use ObjectProvider or Lookup Method Injection to ask the container
for a new instance explicitly inside the method.

M.T.M. Aathif | Spring Boot | 2025


Aspect-Oriented
Programming (AOP)
Introduction to AOP

Aspect-Oriented Programming (AOP)


Is a programming paradigm that allows you to separate cross-cutting concerns
from business logic in application. It focuses on “aspects” like logging,
security, transaction management, and error handling that are applicable
across multiple modules of your application.
▪ In contrast to Object-Oriented Programming (OOP), which focuses on
classes and objects, AOP focuses on “aspects” that cut across these
objects.

Real-World Analogy:
➢ Imagine running a restaurant. The main service is providing food (business
logic), but there are additional concerns like billing, logging the orders, and
checking if a customer has a reservation. These are cross-cutting concerns.
➢ Without AOP: Would need to manually add the billing, logging, and
reservation-checking logic into each part of the service.
➢ With AOP: Can define these concerns separately and apply them to the
relevant parts of application without touching the business logic.

M.T.M. Aathif | Spring Boot | 2025


Problems Without AOP
Without AOP, cross-cutting concerns are mixed with the core business logic,
resulting in:
1. Code Duplication: Common tasks like logging, validation, security checks,
etc., have to be implemented in multiple places.
2. Code Smell: Mixing cross-cutting concerns with the core logic results in
cluttered, hard-to-maintain code.
3. Hard to Maintain: Modifying a common task (e.g., logging mechanism)
requires changing multiple parts of the application.
4. Tight Coupling: Business logic and cross-cutting concerns are tightly
coupled, making it harder to change one without affecting the other.
Real-World Example:
Imagine adding logging to every method in a banking application (like
deposit(), withdraw(), transfer() methods). This creates repetitive code. Using
AOP, can define the logging logic in one place and apply it across methods
without repetition.

AOP Jargons
To master AOP, you must understand these five key terms:
1. Aspect: A module that contains cross-cutting concerns (e.g., logging,
security). An aspect can be applied to multiple classes or methods. (e.g., a
LoggingAspect class).
2. Join Point: A specific point during the execution of the program, such as
the execution of a method or the handling of an exception. In Spring AOP, a
Join Point is always a method execution.
3. Advice: The action taken by an aspect at a particular join point. Think of
this as the "Code" that runs (e.g., "Log the start time").
4. Pointcut: A predicate or expression that matches join points. It defines
where the advice should run (e.g., "Run this for all methods in the Service
layer").
5. Target Object: The object being advised by one or more aspects (your
original Business class).
M.T.M. Aathif | Spring Boot | 2025
Weaving in AOP
Weaving is the process of integrating aspects with the target application. There
are three types of weaving:
1. Compile-time Weaving: The weaving is done during the compilation
process. This is used in AspectJ.
2. Load-time Weaving: The weaving occurs when the class is loaded into the
JVM.
3. Runtime Weaving: The weaving occurs during runtime using frameworks
like Spring AOP.
Real-world Example:
In a logging example, weaving would involve automatically logging method
calls or exceptions in the application without explicitly adding logging code in
each method.

Types of Advices
Spring AOP provides five types of advice based on when the code should run:

Advice Type Description Real-World Example

Runs before the method


@Before Security/Auth checks.
execution.

Runs after the method returns Logging the result of a


@AfterReturning
successfully. transaction.

Runs if the method throws an Sending an alert email to


@AfterThrowing
exception. developers.

Runs after the method, regardless Releasing a database


@After (Finally)
of the outcome. connection.

The most powerful. Surrounds Performance timing


@Around the method. Can control if the (Start clock -> Run ->
method runs at all. Stop clock).

M.T.M. Aathif | Spring Boot | 2025


Configuring AOP with Annotations
To use AOP, you must add the spring-boot-starter-aop dependency to your
[Link].

M.T.M. Aathif | Spring Boot | 2025


Pointcut Expressions
How to write precise pointcuts.
❖ execution(* [Link].*.*(..))
o *: Any return type.
o [Link].*: Any class in that package.
o .*: Any method.
o (..): Any number of arguments.

❖ within([Link]..*): Matches all join points within the service


package and its sub-packages.

❖ @annotation([Link]): Matches only methods


that have a custom @Loggable annotation. (Best practice for selective AOP).

M.T.M. Aathif | Spring Boot | 2025


Building Web Applications
with Spring Boot & Spring
MVC
Introduction to Web Applications
A web application is a software program that runs on a web server and is
accessed through a web browser over the internet or an intranet. It follows a
Client-Server Architecture where the client (browser) sends an HTTP request,
and the server processes the logic to return an HTTP response (HTML, JSON,
or XML).
Evolution of Java Web Apps
1. Servlets & JSP: The foundation of Java web development. Developers
manually managed the request-response lifecycle and configuration.
2. Spring MVC: Introduced a structured Model-View-Controller pattern to
decouple the UI, business logic, and data.
3. Spring Boot: The modern era, eliminating the need for complex XML
configurations and external server deployments.

The Role of Servlets


Servlets are Java classes that handle HTTP requests and generate dynamic
content. In the Spring ecosystem, the most critical component is the
DispatcherServlet.
▪ Front Controller Pattern: The DispatcherServlet acts as a central entry
point.
▪ Request Routing: It intercepts all incoming requests and delegates them
to the appropriate @Controller based on the URL mapping.
▪ Response Handling: Once the controller processes the logic, the
DispatcherServlet helps render the view or convert the data into the
required format (e.g., JSON).

M.T.M. Aathif | Spring Boot | 2025


Evolution of Web Apps in the Java
Ecosystem
➢ Early Java Web Applications:
Initially, Java Web Applications were built using Servlets and JSP (JavaServer
Pages). These were powerful but required manual management of
configurations, session management, and deployment.
➢ Introduction of Spring Framework:
Spring simplified web application development by offering dependency
injection, AOP, and various other features that made it easier to manage cross-
cutting concerns (like logging and transaction management).
➢ Spring MVC:
Spring MVC (Model-View-Controller) is a web framework built on top of the
Spring Framework that helps build robust, flexible web applications by
separating concerns into the model, view, and controller.
➢ Introduction of Spring Boot:
Spring Boot was introduced to simplify the development of Spring-based
applications by eliminating the need for boilerplate code and configuration. It
allows for quick application setup with sensible defaults and an embedded
server.

Types of Web Applications with Spring


▪ Server-Side Rendered (SSR): The server generates the full HTML page
(e.g., using Thymeleaf or FreeMarker). Best for SEO-heavy websites.
▪ RESTful Web Services: The server returns raw data (JSON/XML). This is the
standard for modern Single Page Applications (React, Angular) and Mobile
Apps.
▪ Microservices: Small, independent web services that communicate with
each other to form a large system.

M.T.M. Aathif | Spring Boot | 2025


Spring Boot: The Hero of the Framework
Spring Boot is an extension of the Spring framework that simplifies the initial
setup and development process.
Key Features
▪ Auto-Configuration: Spring Boot automatically configures the application
based on the dependencies present in the [Link].
▪ Starter Dependencies: Bundles multiple libraries into a single dependency
(e.g., spring-boot-starter-web includes Tomcat, Spring MVC, and Jackson).
▪ Embedded Servers: Includes servers like Tomcat or Jetty directly inside
the JAR file, so an external server installation is not required.
▪ Standalone Applications: Allows the creation of stand-alone applications
with minimal dependencies.

Creating and Running a Web Application


The fastest way to start is using Spring Initializr ([Link]).
Implementation Example:

Running the App:


▪ IDE: Right-click the class annotated with @SpringBootApplication and
select "Run".
▪ CLI: Use the Maven wrapper command: ./mvnw spring-boot:run.

M.T.M. Aathif | Spring Boot | 2025


Server Configuration
Spring Boot allows for easy modification of server settings via the
[Link] or [Link] file.
Changing Port and Context Path:
By default, the server runs on port 8080 with a root context path (/).

The application would now be accessed at:


[Link]

Random Server Port:


Useful for testing environments to avoid port conflicts.

Spring Boot will look for an available port at runtime and assign it to the
application.

Demo: Auto-Configuration in Action


Auto-configuration is the "magic" of Spring Boot.
Scenario: Adding spring-boot-starter-data-jpa and a H2 database driver to the
[Link].
o Spring Boot Action: It detects the JPA and H2 libraries.
o Result: It automatically creates a DataSource bean, configures an
EntityManagerFactory, and sets up transaction management without a
single line of manual configuration code
M.T.M. Aathif | Spring Boot | 2025
Project Lombok in
Spring Boot
Introduction to Lombok
Java is often criticized for being "verbose" because of the repetitive code
required for standard objects, such as Getters, Setters, equals(), hashCode(),
and toString() methods. Lombok uses annotations to generate this code at
compile-time, keeping the source file clean.
Key Benefits
▪ Boilerplate Reduction: Eliminates hundreds of lines of code in large
projects.
▪ Readability: Focuses on the data and logic rather than structural noise.
▪ Maintenance: Adding a new field to a class does not require manually
regenerating getters or constructors.

How Lombok Works Internally (Conceptual)


o Lombok hooks into the Java compiler
o Generates bytecode during compile time
o Generated methods are invisible in source code but present in compiled
.class files
o No reflection or runtime processing is involved
This makes Lombok safe for performance-critical applications

M.T.M. Aathif | Spring Boot | 2025


Implementing Lombok in a Spring Boot
Web Application
To use Lombok, it must be added as a dependency in the [Link] and the
Lombok plugin must be installed in the IDE (IntelliJ or Eclipse).
Maven Dependency

Real-World Example: Data Transfer Object (DTO)


Without Lombok, a simple UserDTO requires roughly 50 lines of code. With
Lombok, it is reduced to this:

▪ @Data: A shortcut that combines @Getter, @Setter, @ToString,


@EqualsAndHashCode, and @RequiredArgsConstructor.
▪ @NoArgsConstructor: Generates a constructor with no parameters
(required by many frameworks like JPA).
▪ @AllArgsConstructor: Generates a constructor with one parameter for
every field in the class.

M.T.M. Aathif | Spring Boot | 2025


Core Lombok Annotations
@Getter & @Setter
Automatically generates getters and setters.

@ToString
Generates a readable toString() method.

@EqualsAndHashCode
Generates equals() and hashCode() methods.
Used heavily in:
o Entity comparison
o Caching
o Collections (HashMap, HashSet)

M.T.M. Aathif | Spring Boot | 2025


Constructor Annotations
@NoArgsConstructor: Creates a no-argument constructor.
@AllArgsConstructor: Creates a constructor with all fields.
@RequiredArgsConstructor: Creates a constructor for final and @NonNull
fields.

Commonly used with constructor-based dependency injection in Spring.

@Data – The Power Annotation

Generates:
o Getters & Setters
o toString()
o equals() & hashCode()
o Required constructor
Best Practice
Avoid using @Data on JPA entities due to potential performance and lazy-
loading issues.

M.T.M. Aathif | Spring Boot | 2025


@Builder – Builder Pattern Made Easy

Benefits:
o Readable object creation
o Avoids constructor overloads
o Useful for immutable objects
Real-World Example:
Creating API request/response models cleanly.
@Value – Immutable Objects

o All fields become private final


o No setters
o Thread-safe by design
Commonly used in:
o Response models
o Configuration objects
Null Safety with @NonNull

Throws NullPointerException early and explicitly.

M.T.M. Aathif | Spring Boot | 2025


Demo: @Slf4j for Logging
Logging is a cross-cutting concern often handled via Aspect-Oriented
Programming (AOP) or direct library calls. Traditionally, a logger instance must
be defined manually in every class.
The Traditional Way (Bad)

The Lombok Way (Good)


The @Slf4j annotation automatically creates a log field using the SLF4J
(Simple Logging Facade for Java) framework.

M.T.M. Aathif | Spring Boot | 2025


Important Additional Topics
Lombok with JPA Entities
While @Data is convenient, it can cause performance issues or infinite loops in
JPA @Entity classes due to the generated hashCode() and toString() methods
involving lazy-loaded relationships.

• Best Practice: Use @Getter and @Setter explicitly on Entities instead of


@Data.

The @NonNull Annotation


Applying @NonNull to a field or parameter generates a null check at the start
of the method, throwing a NullPointerException with a clear message if the
value is null.

@Cleanup
Automatically calls the close() method on a resource (like an InputStream or
DatabaseConnection) when the execution leaves the current scope, acting as a
more concise "try-with-resources" block.

M.T.M. Aathif | Spring Boot | 2025


Processing Query
Params & Path
Variables
Modern web development relies heavily on extracting data from URLs to
determine what information to display or process. Spring MVC provides two
primary annotations for this: @RequestParam and @PathVariable.

Query Parameters with @RequestParam


Query parameters are key-value pairs appended to the end of a URL after a
question mark (?). Multiple parameters are separated by an ampersand (&).
They are typically used for filtering, sorting, or pagination.

▪ URL Structure:
[Link]
▪ Annotation Role: @RequestParam binds the value of a specific query
parameter from the request to a method parameter in the controller.
▪ Optional vs. Required: By default, parameters are required. If the
parameter is missing in the URL, Spring throws a 400 Bad Request error.
This can be modified using the required attribute or by providing a
defaultValue.

Example: Product Filtering


In this example, an e-commerce API allows users to filter products by
category.

M.T.M. Aathif | Spring Boot | 2025


Path Variables with @PathVariable
Path variables are part of the URL path itself. They are used to identify a
specific resource. This follows RESTful naming conventions where the URL
represents a specific object hierarchy.

▪ URL Structure: [Link]


▪ Annotation Role: @PathVariable extracts a value from the URI template
and maps it to a method argument. The name in the @GetMapping curly
braces {} must match the method parameter name (or be explicitly defined).

Example: Fetching a Specific User


In this example, a system retrieves details for a single user based on a unique
ID.

Comparison: @RequestParam vs. @PathVariable

Feature @RequestParam @PathVariable

URL Placement Query String (?key=value) URL Path (/resource/value)

Standard Use Filtering, Sorting, Pagination Identifying a specific resource

Structure Dynamic/Optional Static/Hierarchical

Standard for resource


REST Style Less standard for IDs
identification

M.T.M. Aathif | Spring Boot | 2025


Important Additional Topics
1. Handling Multiple Values
If a query parameter contains multiple values (e.g., ?tags=java,spring,web),
Spring can automatically bind them to a List or an Array.

2. Map for Dynamic Parameters


When the number of query parameters is unknown or highly dynamic, all
parameters can be captured into a Map<String, String>.

3. Matrix Variables
Matrix variables are an alternative to query parameters, where variables are
separated by semicolons (;) within the path. While less common, Spring
supports them via the @MatrixVariable annotation.
• URL Example: /cars/color;low=10;high=20
4. Custom Property Editors & Formatters
Spring allows for the conversion of String path/query values into custom Java
objects (like Date, UUID, or custom Enums) using Formatter or Converter
interfaces. This ensures type safety at the controller level.
5. Encoding and Security
Values passed in the URL (especially @PathVariable) should be validated to
prevent Path Traversal attacks. Spring Boot handles standard URL decoding
automatically, but manual validation using @Valid or regex patterns in the
mapping (e.g., /{id:[0-9]+}) is a best practice.

M.T.M. Aathif | Spring Boot | 2025


Validating Input with
Java Bean &
Hibernate Validators
Data validation is the process of ensuring that input data meets specific
criteria before it is processed by the application. It is the first line of defense
against corrupted data and security vulnerabilities.

Importance of Validations in Web


Applications
Validations are critical for maintaining application integrity and security.
▪ Data Integrity: Ensures that only "clean" and logical data is stored in the
database.
▪ Security: Prevents malicious inputs like SQL injection or Cross-Site
Scripting (XSS).
▪ User Experience: Provides immediate feedback to the client when input is
incorrect (e.g., missing email, password too short).
▪ Business Logic Enforcement: Automates simple rules (e.g., "Age must be
over 18") without writing complex if-else blocks in the service layer.

Introduction to Java Bean Validations


(JSR 380)
Java Bean Validation is a standard specification (JSR 380) that allows
developers to express validation constraints via annotations on object fields.
▪ Hibernate Validator: The most common implementation of this
specification and the one used by default in Spring Boot.
▪ Decoupling: Validation logic is defined on the Data Transfer Object (DTO) or
POJO, keeping the Controller and Service layers clean.

M.T.M. Aathif | Spring Boot | 2025


Implementing Validation in a Contact
POJO
To enable validation, the spring-boot-starter-validation dependency must be
included in the [Link].
Adding Annotations to the Class
Commonly used annotations include @NotNull, @Size, @Email, and @Pattern.

Key Concepts:
▪ Annotations: Validation constraints are applied via annotations on object
fields or methods.
▪ Validation Context: Validation occurs when the bean is passed to a
validation framework, either programmatically or automatically (e.g., during
form submission).
Common Annotations:
o @NotNull: Ensures the field is not null.
o @Size(min=, max=): Ensures the length of a string falls within the specified
range.
o @Email: Ensures the string is a valid email address.
o @Min(value), @Max(value): Ensures the number is within a specified range.
o @Pattern(regexp): Validates that a field matches a given regular expression.

M.T.M. Aathif | Spring Boot | 2025


Enabling Validations in the Web
Application
Adding annotations to the POJO is not enough; the Controller must be
instructed to trigger the validation process.
The @Valid Annotation
The @Valid (or @Validated) annotation is placed before the @RequestBody or
model attribute in the Controller method.

Handling Validation Errors Globally


When validation fails, Spring throws a MethodArgumentNotValidException. To
provide a clean, user-friendly response, a Global Exception Handler is
implemented.

M.T.M. Aathif | Spring Boot | 2025


Custom Validators
For more complex validation logic, custom validators can be created by
implementing ConstraintValidator.

Grouping Validations
Sometimes different rules apply to the same POJO (e.g., Password is required
during "Registration" but optional during "Profile Update"). Validation Groups
allow for selective triggering of constraints based on the context.
Bean validation allows defining different groups of constraints for different
validation scenarios.

This allows for different validation rules when creating vs. updating an entity.

M.T.M. Aathif | Spring Boot | 2025


Cross-Field Validation
Cross-field validation is utilized when the validity of one field depends on the
value of another field within the same object. Standard annotations like
@NotNull or @Min cannot handle these scenarios because they only evaluate
a single field in isolation.
Theory
➢ Logic Level: Since the validation logic involves multiple fields, it is typically
implemented at the Class Level rather than the field level.
➢ Implementation: A custom annotation is created, and a corresponding
ConstraintValidator is implemented to compare the fields.
➢ Common Use Cases:
o Ensuring a "Password" and "Confirm Password" field match.
o Verifying that a "Start Date" is chronologically before an "End Date."
o Checking that if a "Shipping Method" is "Express," a "Phone Number" is
provided.
Coding Example: Date Range Validation
In this example, a reservation system ensures the departure date is after the
arrival date.
1. Define the Custom Annotation

2. Implement the Validator

M.T.M. Aathif | Spring Boot | 2025


Database-Level vs. Bean Validation
Professional Spring applications often use a layered approach to validation.
Understanding where to enforce constraints is critical for performance and
security.
Bean Validation (Application Layer)
▪ Bean Validation (JSR 380/Hibernate Validator) occurs within the Java
application before data ever touches the database.
▪ Annotations: @NotNull, @Size, @Email.
▪ Trigger: Activated by the @Valid annotation in the Controller.
▪ Pros: * Fails Fast: Stops processing immediately, saving database
resources.
o User-Friendly: Returns clear, customizable error messages to the client.
o Independent: Works even if the data isn't being saved to a database (e.g.,
calling an external API).
Database-Level Validation (Persistence Layer)
▪ Database-level validation is the final "safety net" defined in the schema
itself.
▪ Annotations (JPA): @Column(nullable = false, length = 50),
@Table(uniqueConstraints = ...).
▪ Trigger: Activated during the SQL INSERT or UPDATE execution.
▪ Pros:
o Absolute Integrity: Guarantees data consistency even if an external tool
(like a database manager) inserts data directly, bypassing the Java code.
o Security: Prevents data corruption at the source.

Feature Bean Validation (@NotNull) Database Validation (@Column)

Location Application Memory (Java) Database Engine (SQL)

Before the Service layer


Timing During the Database Transaction
processes logic

MethodArgumentNotValidExce
Error Type DataIntegrityViolationException
ption

Primary Goal Input filtering and UI feedback Data persistence integrity

M.T.M. Aathif | Spring Boot | 2025


Building Custom
Validations in Spring
MVC
Standard annotations like @NotNull or @Size cover basic requirements, but
production-level applications often require complex, domain-specific
validation logic. Custom validations allow for the encapsulation of business
rules into reusable annotations, keeping controllers and services clean.

Implementing a User Registration Web


Page
A user registration page acts as the entry point for capturing new student or
staff data in the application.
Structural Requirements:
▪ The Model (DTO): A dedicated UserRegistrationDTO is used to capture data
from the form.
▪ The Controller: Handles the GET request to display the registration form and
the POST request to process the submission.
▪ The View: A Thymeleaf or HTML form that binds to the model attributes and
displays validation errors

Building Custom Validations


Custom validations are necessary when a rule cannot be expressed through
standard JSR 380 annotations—for example, ensuring a "Password" and
"Confirm Password" field are identical.
Step 1: Create the Custom Annotation
The annotation defines the "What" of the validation.

M.T.M. Aathif | Spring Boot | 2025


Building Custom Validations
Step 2: Implement the Constraint Validator
The validator defines the "How" of the validation logic.

Step 3: Apply to the Registration DTO


The custom annotation is applied directly to the class.

Handling Custom Validations in the Controller


To trigger the custom logic, the @Valid annotation must be used in the
Controller method.

M.T.M. Aathif | Spring Boot | 2025


Additional Validation Topics
1. Cross-Field Logic for Complex Business Rules
Custom validators are ideal for rules involving logic across multiple fields, such
as verifying that an "Admin Key" is provided only if the "User Role" is set to
"ADMIN".

2. Composing Annotations
Developers can create "Meta-annotations" by combining multiple constraints
into one. For example, a @ValidPassword annotation could internally include
@NotNull, @Size(min=8), and a custom @Pattern for special characters.

3. Database-Driven Custom Validation


Validators can be injected with Spring Beans (like a UserRepository) to check
for real-time data constraints, such as ensuring an email address is not already
registered in the database.

4. Internationalization (i18n) of Error Messages


Instead of hardcoding error strings in the annotation, messages can be moved
to a [Link] file. This allows the registration page to support
multiple languages based on the user's locale.
o Property Entry: [Link]=Passwords must be
identical.

M.T.M. Aathif | Spring Boot | 2025


Spring Web
Scopes
Introduction to Spring Web Scopes
➢ Web scopes manage the visibility and lifecycle of beans based on the
interactions of users with a web application. These beans are not created at
application startup but are instantiated dynamically as web events occur.
➢ In Spring, a bean's scope defines the lifecycle and visibility of a bean in a
web application. While Spring beans can have multiple scopes (singleton,
prototype, etc.), in web applications, the most commonly used scopes are:
▪ Request Scope (@RequestScope)
▪ Session Scope (@SessionScope)
▪ Application Scope (@ApplicationScope)
These scopes are specifically useful for managing stateful beans in a web
environment where each user request or session might require separate or
shared data.

Scope Lifecycle / Visibility Use Case

A single HTTP request; the bean is Tracking specific request


Request
discarded after the response is sent. data like a unique Trace ID.

The duration of an HTTP session;


Storing user preferences or
Session shared across multiple requests from
a shopping cart.
the same user.

The lifecycle of the ServletContext;


Applicatio Global configuration or hit
shared across all users and all
n counters for the entire app.
requests.

M.T.M. Aathif | Spring Boot | 2025


Use Cases for Spring Web Scopes
1. Request Scope (@RequestScope)
A bean in this scope is created once per HTTP request and destroyed once the
request is completed.
Use Case: When data needs to be available for the duration of a request, like
when processing form submissions or user input.
Example: A shopping cart that is temporary and needs to hold data only for a
single HTTP request.

2. Session Scope (@SessionScope)


A bean in this scope is created once per user session and is shared across
multiple requests within the same session.
Use Case: When a bean needs to hold data for a user throughout their session,
like storing user preferences or authentication details.
Example: A user’s shopping cart where items added to the cart should persist
across multiple pages.

3. Application Scope (@ApplicationScope)


A bean in this scope is created once per ServletContext, meaning it is shared
across the entire web application.
Use Case: When data or behavior needs to be shared globally across all
sessions and requests, like a cache or application-wide settings.
Example: Storing a global announcement banner or a counter that tracks the
total number of visitors to the website since the last server restart.

M.T.M. Aathif | Spring Boot | 2025


Demos: Implementing Web Scopes
Demo of @RequestScope inside Easy Web Application
Example: Request Scope Bean for Tracking Form Data
In a simple web application, a bean is scoped to the HTTP request, and each
request to the server gets its own instance of the bean.

Explanation:
o Every time a user submits a form, a new instance of FormData is created to
store the request-specific data.
o Once the request is complete, the FormData bean is discarded.

Demo of @SessionScope inside Easy Web Application


Example: Session Scope Bean for Storing User Information
In this example, a user’s shopping cart or authentication status is stored in a
session-scoped bean, which persists across multiple requests for that user.

Explanation:
o A new instance of UserSession is created when the user’s session starts.
o The bean persists throughout the user’s session, allowing data like the
shopping cart to be carried across multiple requests.
o When the session expires or the user logs out, the session scope bean is
destroyed.
M.T.M. Aathif | Spring Boot | 2025
Demo of @ApplicationScope inside Easy Web Application
Example: Application Scope Bean for Caching
In this example, an application-scoped bean is used to store global settings or
a cache that is shared across all user sessions.

Explanation:
o GlobalCache is available to all users throughout the entire application.
o The cache is shared across all requests and sessions, ensuring that
frequently accessed data is stored once and can be reused.

Difference Between @RequestScope, @SessionScope, and


@ApplicationScope

Feature @RequestScope @SessionScope @ApplicationScope


Lifetime One request One user session Entire application
Shared across all
Visibility One request One session
sessions
Session-specific Global data shared
Use Case Request-specific data
data across the app
Best Use User preferences, Caching, static
Form data, filtering
Case cart data configurations

M.T.M. Aathif | Spring Boot | 2025


Important Web Scope Concepts
1. Scoped Proxies
Because a Singleton bean (like a Controller) is created at startup, it cannot
directly have a Web-scoped bean injected into it (because the Web-scoped
bean doesn't exist yet).
▪ The Solution: Spring uses a Proxy. It injects a "fake" object (proxy) into the
Controller. When a method is called on the proxy, it internally looks up the
real bean in the current Request or Session.
▪ Code Example: @Scope(value = WebApplicationContext.SCOPE_REQUEST,
proxyMode = ScopedProxyMode.TARGET_CLASS).

2. WebSocket Scope
An additional scope used specifically for applications using WebSockets. It
allows for a bean to live for the duration of a single WebSocket connection,
enabling state management for real-time features like chat rooms or live
dashboards.

3. Comparison with Singleton


Unlike Singleton beans, which are thread-safe only if they are stateless, Web-
scoped beans are inherently "thread-safe" for the user because each user (or
request) gets their own isolated instance of the bean.

4. Custom Scopes
Spring allows for the creation of custom scopes by implementing the Scope
interface. This is used in advanced scenarios, such as a "Thread Scope" (one
instance per thread) or a "Batch Scope" for long-running background jobs.

M.T.M. Aathif | Spring Boot | 2025


Global Exception
Handling in Spring
Boot
Introduction to @ControllerAdvice &
@ExceptionHandler
Spring provides powerful tools for handling exceptions in web applications.
Instead of cluttering controllers with multiple try-catch blocks or managing
errors on a case-by-case basis, Spring enables a global and declarative
approach using two annotations: @ControllerAdvice and @ExceptionHandler.
▪ @ExceptionHandler: Used to define methods that handle specific
exceptions in Spring MVC controllers.
▪ @ControllerAdvice: A special controller that provides global exception
handling, making it possible to handle exceptions across the entire
application in one place.
These annotations allow for cleaner, more maintainable error handling in
Spring-based applications.
Theory
@ExceptionHandler Overview
This annotation is used within a specific @Controller to handle exceptions
thrown by its methods. It allows for defining a method that will be executed
whenever a specific exception occurs, returning a custom error response
instead of a standard 500 error.
Key Features:
▪ Can handle specific exceptions like NullPointerException, IOException, or
custom exceptions.
▪ Can specify HTTP status codes using @ResponseStatus or handle the
response body using @ResponseBody.
Common Use Cases of @ExceptionHandler
▪ Handling specific exceptions: For example, catching
ResourceNotFoundException for handling 404 errors.
▪ Returning custom error responses: Providing custom error messages in the
response body.

M.T.M. Aathif | Spring Boot | 2025


@ControllerAdvice Overview
This is a specialization of the @Component annotation that allows for the
application of @ExceptionHandler logic across the entire application. It acts as
an interceptor for exceptions thrown by any controller, promoting the "Don't
Repeat Yourself" (DRY) principle.
Key Features:
▪ Can handle exceptions globally across multiple controllers.
▪ Used to bind exceptions to specific HTTP response statuses.
▪ Can be used to apply common model attributes to all controllers (e.g., for
logging, error details).
Common Use Cases of @ControllerAdvice
▪ Global Exception Handling: To handle exceptions from all controllers in one
place.
▪ Model Enhancement: To add global attributes (like user data, error details)
to all models in the application.

@RestControllerAdvice: A combination of @ControllerAdvice and


@ResponseBody. It ensures that the returned error data is automatically
converted into JSON or XML format.

Problems Without Global Exception


Handling
▪ Code Duplication: Every controller requires its own try-catch blocks or local
@ExceptionHandler methods.
▪ Inconsistent Responses: Different parts of the application might return
different error formats (e.g., one returns a String, another returns a Map).
▪ Leaking Internals: Without proper handling, internal system details or
database stack traces may be exposed to the end user, creating a security
risk.

M.T.M. Aathif | Spring Boot | 2025


Demo: Implementing Global Exception
Handling
Step 1: Create a Custom Error Response POJO
Defining a consistent structure for all error messages.

Step 2: Implement the @RestControllerAdvice Class


This class intercepts exceptions and formats the response.

M.T.M. Aathif | Spring Boot | 2025


Important Exception Handling Topics
1. Handling Validation Errors
Validation failures throw a MethodArgumentNotValidException. This is
commonly handled within the @ControllerAdvice to return a list of specific
field errors to the frontend.

2. Custom Business Exceptions


Instead of using generic Java exceptions, creating specific classes (e.g.,
InsufficientFundsException, UserAlreadyExistsException) allows the Global
Exception Handler to provide more granular HTTP status codes.
3. ResponseStatusException
For simple scenarios where a full @ControllerAdvice is not required, Spring
provides the ResponseStatusException class. It allows developers to throw an
exception with a status code and message directly from the service layer.
• Example: throw new ResponseStatusException(HttpStatus.NOT_FOUND,
"Product not found");
4. Integration with @ResponseStatus
The @ResponseStatus annotation can be applied directly to a custom
exception class. When that exception is thrown, Spring automatically uses the
defined HTTP status code.

5. Customizing the Default Error Attributes


Spring Boot provides a default error page (the "WhiteLabel Error Page"). This
can be disabled or customized by creating a bean that implements the
ErrorAttributes interface, allowing for complete control over the default JSON
error structure provided by the framework.
M.T.M. Aathif | Spring Boot | 2025
Global Exception
Handling in Spring
Boot
Introduction to In-Memory H2 Database
The H2 Database is a lightweight, in-memory database that is often used for
development, testing, and prototyping. It supports SQL and is fully compatible
with JDBC.
In-Memory: By default, data is stored in the system memory (RAM).. This
means all data is lost when the application is stopped or restarted. And making
it ideal for quick testing and development without requiring a full database
setup.
Purpose: It is ideal for development, unit testing, and prototyping because it
requires zero installation or external configuration
Embedded Mode: It can also run in embedded mode, allowing the database to
be packaged within the application.
Ease of Setup: The H2 database can be easily set up and integrated into a
Spring Boot application, reducing overhead and simplifying development.
H2 Console: Spring Boot provides a built-in web-based interface to view and
manage the database tables at runtime.
Real-World Example:
In a Spring Boot application, H2 can be used to simulate a production
database during development or as a temporary data store in applications
where persistent data storage is not required.

M.T.M. Aathif | Spring Boot | 2025


Setup H2 Database in Spring Boot
To enable H2, the h2 runtime dependency and the spring-boot-starter-jdbc (or
data-jpa) dependency must be present in the [Link].
Add H2 Dependency in [Link]

Configuration ([Link])
Spring Boot enables H2 auto-configuration if it detects the library on the
classpath.

Start the Spring Boot application and access the H2 console at:

M.T.M. Aathif | Spring Boot | 2025


JDBC Fundamentals & Challenges
Java Database Connectivity (JDBC) is the standard Java API for connecting to
relational databases.
Problems with Traditional JDBC:
1. Boilerplate Code: Developers must manually open/close connections,
statements, and result sets.
2. Error Handling: Requires repetitive try-catch blocks to handle
SQLException.
3. SQL Injection Risk: Without proper handling, direct SQL queries can
expose applications to SQL injection attacks.
4. Resource Leaks: Failing to close a connection properly can crash the
application.
5. Verbosely Mapping: Manually extracting data from a ResultSet to a Java
object is tedious and error-prone.

Introduction to Spring JDBC


Spring JDBC is part of the Spring Framework that simplifies working with
databases by eliminating repetitive tasks like connection handling, statement
execution, and result processing.
Advantages of Spring JDBC:
1. JdbcTemplate: A central utility class that simplifies database interaction
by handling the creation and closing of database connections, executing
SQL queries, and mapping results to Java objects.
2. Exception Handling: Spring JDBC provides consistent exception handling,
converting database-related errors into DataAccessException, which is a
runtime exception.
3. Declarative Transaction Management: Integrated with Spring's
transaction management system.

M.T.M. Aathif | Spring Boot | 2025


Deep Dive on Usage of JdbcTemplate
The JdbcTemplate is the core class in Spring JDBC that facilitates interacting
with relational databases. It reduces boilerplate code and simplifies querying,
updating, and interacting with a database.
Common JdbcTemplate Operations:
▪ Query Execution: Executes a SQL query and processes the results.
▪ Update Execution: Executes insert, update, or delete SQL statements.
▪ Batch Operations: Executes batch updates to optimize database access.

Saving Contact Message into DB using JdbcTemplate Insert Operation


Example: Inserting Data into Database

• The update method is used to perform insert, update, or delete operations.


• The values for name, email, and message are dynamically set from the
Contact object.

Display Contact Messages from DB using JdbcTemplate Select Operation


Example: Selecting Data from Database

• This code queries all rows from the contact table and returns a list of
Contact objects.
• The BeanPropertyRowMapper maps the SQL result set to Java beans.
M.T.M. Aathif | Spring Boot | 2025
Update Contact Messages Status using JdbcTemplate Update Operation
Example: Updating Data in Database

• The update method is used to execute an update query.


• This method updates the status of a specific contact based on its ID.

Implementing AOP for Data Logging


Aspect-Oriented Programming (AOP) can be used in conjunction with Spring to
separate cross-cutting concerns, such as logging or transaction management,
from the core business logic.
Monitor or log database operations without polluting the repository classes.

• The @Aspect annotation defines an aspect for logging database queries.


• The @Before annotation ensures logging occurs before a method in the
ContactDao is executed.
Spring Data & Spring
Data JPA
Introduction to Spring Data & Spring Data
JPA
In Spring applications, data access is crucial for interacting with databases.
While Spring JDBC allows direct interaction with databases using SQL, it
comes with certain challenges such as boilerplate code, manual mapping of
results, and transaction management. This is where Spring Data and Spring
Data JPA come into play, making database interaction easier, more flexible,
and efficient by providing abstraction and leveraging Object-Relational
Mapping (ORM).
Problems with Spring JDBC & How ORM Frameworks Solve These
Problems

While JdbcTemplate reduces boilerplate, it still presents challenges in


complex enterprise applications.

Challenges with Spring JDBC:

▪ Manual Mapping: Developers must manually map ResultSet rows to Java


objects using a RowMapper.
▪ SQL Maintenance: Large applications require managing hundreds of raw
SQL strings, which is error-prone during schema changes.
▪ Relationship Complexity: Handling SQL for complex object relationships
(One-to-Many, Many-to-Many) is difficult and requires extensive manual
coding.

How Object-Relational Mapping (ORM) Solves These:

ORM frameworks like Hibernate bridge the gap between the object-oriented
world (Java classes) and the relational world (SQL tables).
▪ Automatic Persistence: Java objects are automatically mapped to
database tables.
▪ HQL/JPQL: Allows querying using object names instead of table names.
▪ Abstraction: Developers focus on business logic rather than database-
specific SQL syntax.
▪ Transaction Management: Simplifies transaction management and
handling of database resources.

M.T.M. Aathif | Spring Boot | 2025


Introduction to Spring Data
Spring Data is an umbrella project that aims to provide a unified way to access
data across different types of databases (SQL, NoSQL, Graph, etc.). It
eliminates the need to write implementation code for the repository layer.
Instead, the developer defines an interface, and Spring Data provides the
implementation at runtime.
Main Features:
▪ Simplifies repository-based data access using interfaces.
▪ Automatically implements repository interfaces at runtime.
▪ Integrates seamlessly with JPA, MongoDB, Cassandra, and other data
sources.
▪ Supports pagination and sorting, even for complex queries.

Deep Dive into Repository Hierarchy


Spring Data JPA provides several built-in interfaces. Choosing the correct one
depends on the required functionality.

Interface Purpose

The base interface; provides no methods. Used to


Repository<T, ID>
keep the repository domain-specific.

Provides basic CRUD operations (save, findById,


CrudRepository<T, ID>
findAll, delete).

PagingAndSortingRepository Extends CrudRepository and adds methods to


<T, ID> retrieve entities using Pagination and Sorting.

Extends both PagingAndSortingRepository and


JpaRepository<T, ID> QueryByExampleExecutor. It adds JPA-specific
operations like flush() and deleteInBatch().

M.T.M. Aathif | Spring Boot | 2025


Deep Dive into Repository Hierarchy
Spring Data provides several key interfaces to interact with the database
efficiently:
1. Repository
• The base interface for Spring Data repositories.
• Typically, custom methods can be defined here.

2. CrudRepository
• Extends Repository and provides methods for CRUD operations (Create,
Read, Update, Delete).
• Common methods include save(), findById(), delete(), and findAll().

3. PagingAndSortingRepository
• Extends CrudRepository and provides additional methods for pagination
and sorting.
• This is useful for applications that require large datasets, where retrieving
all records at once is inefficient.

4. JpaRepository
• Extends PagingAndSortingRepository and adds JPA-specific methods like
flush() and saveAndFlush().
• Best suited for applications that use JPA and Hibernate as the persistence
provider.

M.T.M. Aathif | Spring Boot | 2025


Introduction to Spring Data JPA
Spring Data JPA is a part of Spring Data that integrates JPA (Java Persistence
API) into Spring applications. JPA is an API that allows developers to interact
with databases using Java objects (entities) instead of raw SQL.
Main Features:
▪ Automatic repository implementation: Spring Data JPA provides the
ability to create repository interfaces, and Spring will generate the
implementation automatically.
▪ JPA annotations: Entities are annotated with @Entity and other JPA-
specific annotations to map them to database tables.
▪ Query Methods: Spring Data JPA supports creating queries using method
names and allows the use of JPQL (Java Persistence Query Language).

Introduction to Spring Data JPA


To migrate, the manual JdbcTemplate implementation is replaced with a
Spring Data interface.
Steps for Migration:
1. Dependencies: Replace spring-boot-starter-jdbc with spring-boot-starter-
data-jpa.
2. Entity Mapping: Annotate the POJO class with @Entity and @Id.
3. Repository Definition: Create an interface extending JpaRepository.
4. Service Update: Inject the new Repository interface into the service layer
instead of the JdbcTemplate-based repository.
Example Migration:

M.T.M. Aathif | Spring Boot | 2025


Deep Dive: Derived Query Methods
One of the most powerful features of Spring Data JPA is the ability to generate
SQL queries based on the method names in the repository interface.
Method Naming Conventions:
Methods are named in a specific way, and Spring automatically generates the
SQL query based on the method name.
Common prefixes include:
o findBy, readBy, queryBy: For finding records based on fields.
o countBy: For counting records matching a condition.
o deleteBy: For deleting records based on fields.
Examples:

M.T.M. Aathif | Spring Boot | 2025


Additional Important Topics
1. Custom Queries with @Query
When method names become too long or complex, the @Query annotation
allows for writing custom JPQL (Java Persistence Query Language) or Native
SQL.

2. Transaction Management
Spring Data JPA methods are @Transactional by default. For custom
repository methods that modify data (Update/Delete), the @Modifying and
@Transactional annotations must be added.

3. Auditing with @CreatedDate and @LastModifiedDate


Spring Data JPA can automatically track when a record was created or last
updated. This is enabled by adding
@EntityListeners([Link]) to the entity.

M.T.M. Aathif | Spring Boot | 2025


Additional Important Topics
4. Dynamic Filtering with Specifications
For applications requiring advanced search filters (e.g., searching by multiple
optional fields), the Criteria API or Specifications allow for building dynamic
WHERE clauses programmatically.

5. Pagination and Sorting in Spring Data JPA


Pagination and sorting are essential for managing large datasets. Spring Data
JPA provides support for both through the Pageable and Sort interfaces.

M.T.M. Aathif | Spring Boot | 2025


Auditing Support
with Spring Data
JPA
In production-grade applications, tracking when a record was created, who
created it, and when it was last modified is a critical requirement for security,
compliance, and debugging. Spring Data JPA provides built-in auditing support
to automate these tasks, eliminating the need to manually set these values in
the service layer.

Introduction to Auditing Support


Auditing allows an application to automatically capture and maintain tracking
information about its entities. Instead of manually writing code to set
timestamps or user IDs before every save operation, Spring Data JPA
intercepts the entity lifecycle and injects these values.
Key Benefits:
▪ Consistency: Every entity follows the same tracking rules without
developer intervention.
▪ Reduced Boilerplate: Removes repetitive code like
[Link]([Link]()) from the service layer.
▪ Accountability: Provides a clear history of who changed what and when,
which is vital for enterprise audit trails.
Core Auditing Annotations:
▪ @CreatedDate: Captures the date and time when the entity was first
created.
▪ @LastModifiedDate: Captures the date and time when the entity was last
updated.
▪ @CreatedBy: Captures the identity of the user who created the entity
(requires integration with Spring Security).
▪ @LastModifiedBy: Captures the identity of the user who last modified the
entity.

M.T.M. Aathif | Spring Boot | 2025


Implementing Automatic Auditing
Implementing auditing requires four main steps to ensure the application
correctly captures and persists the metadata.
Step 1: Enable JPA Auditing
The auditing feature must be explicitly activated by adding the
@EnableJpaAuditing annotation to a configuration class

Step 2: Create a Base Entity (Optional but Recommended)


A common pattern is to create a @MappedSuperclass to hold auditing fields.
This allows other entities to inherit auditing functionality without repeating
field definitions.

• The @EntityListeners([Link]) annotation tells Spring


to listen for changes to the entity and automatically update the auditing
fields.
• The @CreatedDate, @CreatedBy, @LastModifiedDate, and @LastModifiedBy
annotations are placed on the corresponding fields in the entity to mark
them as fields that should be automatically populated by Spring Data JPA.
M.T.M. Aathif | Spring Boot | 2025
Step 3: Implement AuditorAware (For User Tracking)
To support @CreatedBy and @LastModifiedBy, a bean must be created that
tells Spring who the current user is. This is typically pulled from the
SecurityContext.

Step 4: Apply to Business Entities


The final step is to have business entities extend the BaseEntity.

M.T.M. Aathif | Spring Boot | 2025


Additional Important Auditing Topics
1. The AuditingEntityListener
This is a standard JPA Entity Listener provided by Spring Data. It uses the
@PrePersist and @PreUpdate callbacks to set the date and user information
just before the SQL INSERT or UPDATE is sent to the database.
Auditing with @PrePersist and @PreUpdate
While Spring Data JPA handles automatic auditing, there might be cases where
manual auditing logic is required. This can be done using JPA lifecycle
annotations like @PrePersist and @PreUpdate.

2. Integration with Spring Security


The power of auditing is truly realized when paired with Spring Security. The
AuditorAware interface bridges the gap between the persistent layer (JPA) and
the security layer, allowing the system to log the actual username of the
person performing the action.
3. Using @Temporal for Legacy Apps
In modern applications, [Link] is preferred. However, when
working with older [Link] or [Link] types, the @Temporal
annotation must be used to specify the precision (DATE, TIME, or TIMESTAMP)
in the database.
4. Database-Level Default Values vs. Application Auditing
While a database can set a default value like DEFAULT
CURRENT_TIMESTAMP, application-level auditing is more flexible. It allows
for complex logic, such as using different time zones or capturing non-
database information like the "Source of Request" (web vs. mobile).
M.T.M. Aathif | Spring Boot | 2025
Deep Dive into OneToOne
Relationships, Fetch
Types, and Cascading
In Object-Relational Mapping (ORM), managing how entities relate to one
another is fundamental for data integrity and performance. A OneToOne
relationship represents a link where one instance of an entity is associated
with exactly one instance of another entity.

Database Schema for User Registration


In a production-level registration process, user data is often normalized across
multiple tables to ensure organized data storage.
▪ PERSON Table: Stores core identity details (name, email, password).
▪ ADDRESS Table: Stores location details (street, city, zip code).
▪ ROLES Table: Stores authorization levels (ADMIN, STUDENT, STAFF).
Example: Creating Tables for User Registration

• Person table holds user details.


• Address table has a foreign key to Person to store address information for
the specific user.
• Roles table holds roles assigned to users.

M.T.M. Aathif | Spring Boot | 2025


Introduction to One-to-One Relationships
A OneToOne relationship occurs when one record in Table A is associated with
exactly one record in Table B.
This relationship is commonly used when an entity has a corresponding entity
that holds extra information (e.g., user profile and user settings).
▪ @OneToOne: Defines a one-to-one relationship between two entities.
▪ mappedBy: Specifies the inverse side of the relationship.
Example: Person and Address
In the application, a Person has exactly one primary Address, and that Address
belongs to only one Person.

One-to-One Configuration (Theory)


Configuring these relationships in Spring Data JPA requires defining the
Owning Side and the Inverse Side.
❖ Owning Side: The entity that contains the Foreign Key (FK) column in the
database. This is usually where the @JoinColumn annotation is placed.
❖ Inverse Side: The entity that is linked to the owner. It uses the mappedBy
attribute to indicate that the relationship is managed by the other side.
❖ Bidirectional vs. Unidirectional:
o Unidirectional: Only the Person knows about the Address.
o Bidirectional: Both entities have a reference to each other, allowing
navigation from either side.
Deep Dive: Fetch Types
Fetch types determine when the related data is loaded from the database into
the Java application.
Fetch Type Strategy Default for... Behavior
@OneToOne, The related entity is fetched immediately when
EAGER Immediate
@ManyToOne the owning entity is loaded (default).

@OneToMany, Related data is only fetched when the getter


LAZY On-Demand
@ManyToMany method (e.g., getAddress()) is called.

M.T.M. Aathif | Spring Boot | 2025


Deep Dive: Cascade Types
Cascading allows state changes to be propagated from a parent entity to its
child entities. If a Person is saved, the associated Address can be saved
automatically.
▪ PERSIST: When the parent is saved, the child is also saved.
▪ REMOVE: When the parent is deleted, the child is also deleted (Orphan
Removal).
▪ MERGE: When the parent state is updated, the child state is updated.
▪ ALL: Applies all the above operations.

Implementation Example (Coding)


Address Entity (Inverse Side)

Person Entity (Owning Side)

M.T.M. Aathif | Spring Boot | 2025


Implementation Example: Breakdown
1. @OneToOne
This annotation defines the multiplicity of the relationship. It informs
Hibernate that one instance of Person is strictly linked to exactly one instance
of Address.
2. mappedBy (The Inverse Side)
▪ What it does: It tells JPA that the relationship is already mapped by a field
in the other entity.
▪ Why it is used: It prevents the creation of a Foreign Key in both tables. In
the
▪ example above, mappedBy = "address" refers to the address field inside the
Person class.
3. fetch = [Link]
▪ What it does: It controls when the related data is loaded.
▪ Behavior: When a Person is loaded from the database, the Address data is
not fetched immediately. It is only retrieved if the code explicitly calls
[Link](). This saves memory and improves performance in
high-traffic applications.
4. cascade = [Link]
▪ What it does: It propagates state changes from the parent to the child.
▪ Behavior: If a Person is saved, deleted, or updated, the associated Address
will automatically undergo the same operation. Without this, the Address
would have to be saved manually before saving the Person.
5. @JoinColumn
This annotation is used to define the physical mapping of the Foreign Key in
the database table.
▪ name = "address_id": This defines the actual column name that will appear
in the PERSON table to hold the link to the Address.
▪ referencedColumnName = "id": This specifies the column in the ADDRESS
table that this Foreign Key points to (usually the Primary Key of the target
table).

M.T.M. Aathif | Spring Boot | 2025


Unidirectional One-to-One Relationship
In a unidirectional relationship, only one entity (the owner) contains a
reference to the other. The target entity has no knowledge of the owner.
Coding Example
The Target (Address): This class is a standard POJO with no reference back to
the Person.

The Owner (Person): The Person "owns" the relationship by defining the link.

Breakdown
• Navigation: You can call [Link](), but there is no way to call
[Link]().
• Database: A column named address_id is created in the PERSON table.
• Simplicity: This is easier to maintain as there is only one side to update.

M.T.M. Aathif | Spring Boot | 2025


Bidirectional One-to-One Relationship
In a bidirectional relationship, both entities hold a reference to each other.
This allows you to navigate the relationship from either side in your code.
Coding Example
The Inverse Side (Address): Uses mappedBy to tell JPA that the relationship is
already defined elsewhere.

The Owning Side (Person): The side that physically holds the Foreign Key.

Breakdown
• mappedBy: This is the most critical attribute for bidirectional links. It must
be placed on the Inverse Side (Address) and points to the field name in the
Owning Side (Person).
• Navigation: You can move from Person to Address ([Link]())
and from Address back to Person ([Link]()).
• Database: Only one Foreign Key is created (in the PERSON table). Without
mappedBy, JPA would try to create a Foreign Key in both tables, which is
inefficient.
• Synchronization: When updating the relationship, both sides must be
updated in the Java code (e.g., [Link](addr) AND
[Link](person)) to keep the memory state consistent with the
database.
M.T.M. Aathif | Spring Boot | 2025
Additional Important Topics
1. The N+1 Select Problem
Even with LAZY fetching, loading a list of 100 Persons and then accessing each
of their Addresses can trigger 101 database queries.
Solution: Use Entity Graphs or JOIN FETCH in JPQL to load related entities in a
single query.
2. Orphan Removal
In a OneToOne relationship, an "orphan" is a child entity that is no longer
associated with its parent. Setting orphanRemoval = true ensures that when
the link is broken, the child is automatically deleted from the database.

3. Shared Primary Key


A Shared Primary Key is a design where the child table (ADDRESS) does not
have its own independent ID generator. Instead, it uses the exact same ID
value as the parent table (PERSON).

M.T.M. Aathif | Spring Boot | 2025


Additional Important Topics
4. Handling Circular Dependencies with Lombok
When using @Data or @ToString on both sides of a bidirectional relationship,
an infinite loop is triggered. [Link]() calls [Link](), which
calls [Link]() again, eventually causing a StackOverflowError.
Code Example: The Best Practice
Use @[Link] on the inverse side to break the circular reference.

M.T.M. Aathif | Spring Boot | 2025


Deep Dive into
OneToMany and
ManyToOne Relationships
ORM frameworks like Spring Data JPA provide an easy and efficient way to
handle relationships between entities. In this section, the focus is on
OneToMany and ManyToOne relationships, which are often used to represent
hierarchical data, such as classes and students or orders and products.

Introduction to OneToMany & ManyToOne


Mappings
Theory
▪ @OneToMany: Defines a one-to-many relationship where one entity is
related to multiple instances of another entity. For example, one class can
have multiple students.
▪ @ManyToOne: Defines a many-to-one relationship where many instances
of an entity are related to one instance of another entity. For example,
multiple students are enrolled in one class.

Use Case:
A School application has Students and Classes.
• One Class can have multiple Students (OneToMany).
• Many Students can belong to one Class (ManyToOne).

M.T.M. Aathif | Spring Boot | 2025


Implement OneToMany & ManyToOne
Configurations Inside Entity Classes
In Spring Data JPA, OneToMany and ManyToOne relationships are typically
mapped using JPA annotations like @OneToMany, @ManyToOne,
@JoinColumn, and @MappedBy.
Example: Class and Student Entities

M.T.M. Aathif | Spring Boot | 2025


Implementation Breakdown
1. The Parent: Class Entity (Inverse Side)
The Class entity represents the "One" side of the relationship. It is considered
the Inverse Side because it does not physically store the relationship details in
its database table.
▪ @OneToMany: This annotation specifies that one instance of this entity is
associated with multiple instances of the Student entity.
▪ mappedBy = "studentClass": This is the most critical attribute for the
inverse side. It tells JPA that the relationship is managed by the
studentClass field inside the Student class. It prevents the creation of a
redundant join table or extra foreign key in the Class table.
▪ fetch = [Link]: This defines the loading strategy. When a Class
object is loaded, the list of students is not retrieved from the database
immediately. It is only fetched if getStudents() is called, which optimizes
performance.
▪ cascade = [Link]: This ensures that if a new Class is
saved, any new Student objects added to its list are also automatically
saved (persisted) to the database.
▪ targetEntity = [Link]: Explicitly defines the class type of the
elements in the collection.
2. The Child: Student Entity (Owning Side)
The Student entity represents the "Many" side. It is the Owning Side because it
physically contains the Foreign Key that links the two tables.
▪ @ManyToOne: Specifies that many students can belong to one single class.
▪ fetch = [Link]: Similar to the parent side, the Class details are
not loaded until explicitly accessed via getStudentClass().
▪ optional = true: Indicates that a student is allowed to exist without being
assigned to a class.
▪ @JoinColumn: This annotation defines the physical database mapping for
the relationship.
o name = "class_id": This is the name of the Foreign Key column that will be
created in the STUDENT table.
o referencedColumnName = "classId": This specifies the column in the
CLASS table that the foreign key points to (the Primary Key of the parent).
o nullable = true: Matches the optional = true logic, allowing the class_id
column in the database to contain null values.

M.T.M. Aathif | Spring Boot | 2025


Additional Important Topics
1. Using Set vs List
For @OneToMany relationships, using [Link] is a best practice.
• Why: Set prevents duplicate entries and is more efficient for Hibernate to
manage during updates and deletes compared to a List.

2. Synchronization Methods (Defensive Coding)


In bidirectional relationships, it is necessary to keep both sides of the
relationship in sync in the Java memory.

M.T.M. Aathif | Spring Boot | 2025


Deep Dive into
ManyToMany
Relationships
Introduction to ManyToMany Relationships
In a relational database, a ManyToMany relationship cannot be implemented
using a simple Foreign Key in one of the two tables. Instead, it requires a Join
Table (also known as a Link Table or Junction Table).
▪ The Join Table: This intermediate table contains Foreign Keys from both
associated tables (e.g., student_id and course_id).
▪ Directionality: These can be unidirectional (one entity knows about the
other) or bidirectional (both entities have collections of each other).
▪ Logical Association: One Student can have a Set of Courses, and one
Course can have a Set of Students.

Implementing ManyToMany Configurations


To implement this in Spring Data JPA, the @ManyToMany annotation is used
along with @JoinTable to define the underlying database structure.
The "Owning" Side: Course Entity
The owning side defines the Join Table details using the @JoinTable
annotation.

The "Inverse" Side: Student Entity


The inverse side uses the mappedBy attribute to reference the collection in the
owning entity.

M.T.M. Aathif | Spring Boot | 2025


The "Inverse" Side: Student Entity
The inverse side uses the mappedBy attribute to reference the collection in the
owning entity.

Breakdown
• @JoinTable: Defines the name of the link table (student_courses) that
resides in the database.
• joinColumns: Specifies the Foreign Key column for the owning side
(course_id).
• inverseJoinColumns: Specifies the Foreign Key column for the inverse side
(student_id).
• mappedBy = "students": Tells JPA that the Student side is not the owner of
the relationship; the relationship is mapped by the students field in the
Course class.
• [Link]: Essential for performance; courses or students are only
loaded from the database when explicitly accessed.

M.T.M. Aathif | Spring Boot | 2025


Additional Important Topics
Join Table with Extra Columns
In many real-world scenarios, the join table needs extra data (e.g., the date a
student enrolled or their grade).
▪ The Problem: @ManyToMany does not support extra columns in the join
table.
▪ The Solution: Break the ManyToMany into two OneToMany relationships
with an intermediate entity (e.g., an Enrollment entity).
In this pattern, a new entity (e.g., Enrollment) is created to represent the "link"
between Student and Course, allowing for the storage of extra columns.
1. The Intermediate Entity: Enrollment
This entity holds the extra data and links back to both the Student and the
Course using @ManyToOne.

M.T.M. Aathif | Spring Boot | 2025


2. The Student Entity
The Student no longer points directly to Course. Instead, it has a collection of
Enrollment objects.

3. The Course Entity


Similarly, the Course entity points to the Enrollment records rather than the
students.

Key Differences & Breakdown


• Relationship Shift: The direct link between Student and Course is removed.
It is replaced by a bridge: Student Enrollment Course.
• Data Control: Extra metadata (like enrollmentDate or grade) is now easily
accessible as fields within the Enrollment object.
• Cascade Logic: Operations like saving or deleting can be cascaded from the
Student or Course down to the Enrollment.
• Querying: To find a student's grade in a course, the Enrollment table is
queried directly, which is more efficient than navigating a hidden join table.
M.T.M. Aathif | Spring Boot | 2025
Sorting & Pagination in
Spring Data JPA
Introduction to Pagination
Pagination is essential for handling large datasets, as it splits the data into
smaller, manageable chunks or pages. Spring Data JPA provides the
PageRequest class to define the page number and page size (i.e., the number
of records per page).
Key Points:
▪ Pageable Interface: The Pageable interface is used to pass the page number
and page size to the repository method.
▪ Page Class: The Page class represents the result of a paginated query and
contains methods to get the content, total number of elements, and total
pages.
Why Pagination is Critical:
▪ Resource Optimization: Reduces the payload size transmitted over the
network.
▪ Memory Management: Prevents the application from loading millions of
rows into the JVM.
▪ Latency: Faster response times for end-users by only fetching a small
subset of data (e.g., 20 items at a time).

M.T.M. Aathif | Spring Boot | 2025


Implementing Pagination & Dynamic
Sorting
Spring Data JPA provides the Pageable interface and the PageRequest
implementation to combine pagination and sorting into a single operation.
Coding Example: Combined Request
In this example, a school dashboard fetches a paginated list of students,
sorted dynamically.
1. Repository Interface

2. Service Implementation

• [Link](page, size, sort) creates a pageable object with the


requested page number and page size, along with the dynamic sorting.
• The findAll(pageable) method is used to fetch a specific page of data with
the applied sorting.
Understanding the Page<T> Object
The Page object returned by the repository contains more than just the data. it
provides metadata useful for the frontend:
▪ getContent(): The list of items for the current page.
▪ getTotalPages(): Total number of pages available.
▪ getTotalElements(): Total number of records in the database.
▪ getNumber(): Current page number.
▪ hasNext() / hasPrevious(): Boolean checks for navigation.

M.T.M. Aathif | Spring Boot | 2025


Additional Important Topics
1. Zero-Indexed Pagination
Spring Data JPA's PageRequest internally uses 0-based indexing, meaning the
first page is represented by 0. In production environments, APIs usually
receive 1-based page numbers from the frontend (e.g., Page 1) to remain user-
friendly. The logic must subtract 1 before passing it to the repository.
Best For: Traditional paginated tables with "Go to Page X" buttons.

2. Slicing vs. Paging


While a Page<T> returns the total number of elements and pages (requiring an
expensive COUNT(*) query), a Slice<T> only knows if a "next" slice exists. This
is significantly more performant for large datasets where a total count is not
required, such as in "Infinite Scroll" features.
Best for: Mobile apps, social media feeds, and infinite scrolling.

M.T.M. Aathif | Spring Boot | 2025


3. Sorting on Multiple Fields
The Sort object supports chaining, allowing for primary, secondary, and
tertiary sorting criteria. This is essential when the primary field contains many
identical values (e.g., sorting by "Last Name" then "First Name").
Best for: Complex data views with overlapping field values.

4. Handling Case Sensitivity


By default, database sorting is case-sensitive (e.g., "apple" might appear after
"Zebra"). To ensure a proper alphabetical order regardless of capitalization,
the ignoreCase() modifier is applied.
Best for: Consistent alphabetical listing for user-entered text.

M.T.M. Aathif | Spring Boot | 2025


Writing Custom Queries in
Spring Data JPA
Introduction to Custom Queries
Spring Data JPA simplifies data access by allowing developers to define
custom queries with minimal code. While Spring Data JPA provides built-in
methods for basic CRUD operations, custom queries are often necessary for
more complex data retrieval. Custom queries can be written using the @Query
annotation, @NamedQuery, @NamedNativeQuery, or JPQL (Java Persistence
Query Language).
These annotations allow for flexibility in writing queries, whether they are for
selecting data, updating records, or executing native SQL queries. This
approach ensures that Spring developers can write efficient, readable, and
maintainable custom queries within the Spring Data JPA framework.
Custom queries are used when method name conventions become too long or
when specific database optimizations are required.
▪ JPQL (Java Persistence Query Language): An object-oriented query
language that refers to entities and their properties rather than database
tables and columns.
▪ Native SQL: Raw SQL queries executed directly against the database
schema.
▪ Annotations:
@Query: Defines a query directly in the repository interface.
@NamedQuery: A pre-defined JPQL query declared at the Entity level.
@NamedNativeQuery: A pre-defined raw SQL query declared at the Entity
level.

M.T.M. Aathif | Spring Boot | 2025


Writing Custom Queries
Writing Custom Queries using @Query
The @Query annotation allows developers to define custom JPQL or native
SQL queries directly in the repository interface. It can be used for SELECT,
UPDATE, and DELETE operations.
Implementation Example (JPQL)
This example finds students by student name

Custom Update Queries


By default, @Query is intended for SELECT operations. To perform UPDATE,
DELETE, or INSERT, additional annotations are required to manage the
transaction and the persistence context.
▪ @Modifying: Informs Spring Data JPA that the query will modify the data
(e.g., UPDATE/DELETE).
▪ @Transactional: Ensures the operation runs within a transaction; it is
required for all modifying queries.

Custom DELETE Query

M.T.M. Aathif | Spring Boot | 2025


Deep Dive: @NamedQuery and
@NamedNativeQuery
Theory
@NamedQuery: A JPQL query defined in the entity class and registered at
runtime. It is used for predefined queries that are reusable and are tied to the
entity.
@NamedNativeQuery: Similar to @NamedQuery but allows using native SQL
instead of JPQL.
These queries are typically defined as part of the entity class, making them
reusable across the application.
Example: Defining a @NamedQuery

• @NamedQuery is defined in the entity class (Student) to select a student by


name.
• The query can be referenced using its name ([Link]) in the
repository.
Example: Using @NamedQuery in Repository

M.T.M. Aathif | Spring Boot | 2025


Example: Defining a @NamedNativeQuery

• @NamedNativeQuery defines a native SQL query that retrieves students


based on age.
• The resultClass attribute maps the query result to the Student entity.
Example: Using @NamedNativeQuery in Repository

M.T.M. Aathif | Spring Boot | 2025


Additional Important Query Topics
1. Positional vs. Named Parameters
While positional parameters map arguments based on their order, Named
Parameters use specific labels, making the code easier to read and maintain,
especially in queries with many variables.
Code Example

2. Native Queries in @Query


Native queries allow the execution of raw SQL directly against the database.
This is used when specific database features or performance optimizations are
required that are not supported by JPQL.
Code Example

M.T.M. Aathif | Spring Boot | 2025


3. Projections with Custom Queries
Projections are used to retrieve only a subset of columns from a table. This is a
production best practice for optimizing memory and network performance by
avoiding the loading of entire entity objects.
Code Example (Interface Projection)
• Define the Projection Interface

• Use in Repository

4. SpEL in @Query
Spring Expression Language (SpEL) allows for dynamic query generation. Using
#{#entityName} is particularly useful in base repository classes or when the
entity name might change, as it automatically resolves to the correct entity
type at runtime.
Code Example

M.T.M. Aathif | Spring Boot | 2025


Building RESTful Web
Services with Spring
Introduction to REST Services
REST (Representational State Transfer) is an architectural style for designing
networked applications. It uses HTTP methods like GET, POST, PUT, DELETE,
and PATCH to interact with resources, typically in the form of JSON or XML
data. In a Spring Framework application, RESTful services are built using
Spring MVC and Spring Boot to expose CRUD (Create, Read, Update, Delete)
operations to clients in a lightweight and scalable manner.
REST services are stateless and centered around Resources identified by URIs.
▪ Statelessness: Each request from a client contains all the information
necessary to understand and process the request.
▪ Standard Methods: Uses HTTP verbs like GET (Read), POST (Create), PUT
(Update), and DELETE (Remove).
▪ Media Types: Data is typically exchanged in JSON (JavaScript Object
Notation) or XML.

The Evolution of REST in Spring


Spring MVC Style with @ResponseBody
In early Spring versions, REST was achieved by adding @ResponseBody to
standard controller methods.
▪ Theory: This annotation tells Spring that the return value of the method
should be bound directly to the web response body, skipping the "View
Resolver".
▪ Manual Approach: Every method requires the annotation, which leads to
repetitive code.
The Modern Way: @RestController
@RestController is a specialized version of @Controller that includes
@ResponseBody by default.
▪ Advantage: It simplifies the creation of RESTful web services by assuming
every method returns a data object instead of a view.

M.T.M. Aathif | Spring Boot | 2025


Implement REST Service
Implement REST Service Using Spring MVC Style & @ResponseBody
Using Spring MVC style REST services, the @RequestMapping annotation maps
the HTTP request to the method, and @ResponseBody is used to return the
response.
Example: Implementing a REST Service for Fetching Users

Implement REST Services Using @RequestBody Annotation


▪ @RequestBody is used to map the request body to a Java object. It is
commonly used when the request contains JSON or XML data that needs to
be converted into a Java object.
▪ This is typically used with POST, PUT, or PATCH requests where the body
contains data to be processed.
Example: Using @RequestBody to Map Incoming JSON to Java Object

M.T.M. Aathif | Spring Boot | 2025


Implement REST Services Using @RestController Annotation
▪ @RestController is a convenience annotation that combines @Controller
and @ResponseBody. It is specifically designed for REST services where the
return type is automatically written to the response body.
▪ This annotation simplifies the implementation of RESTful web services by
eliminating the need to use @ResponseBody for each method.
Example: Using @RestController for Creating REST Services

M.T.M. Aathif | Spring Boot | 2025


Advanced REST Features
1. Global Error Handling: @RestControllerAdvice
This approach centralizes exception handling, ensuring that every error returns
a consistent JSON structure instead of a raw stack trace.
Code Example
The Custom Error Response:

The Global Interceptor:

• @RestControllerAdvice handles all exceptions globally.


• @ExceptionHandler maps specific exceptions to custom error responses.

M.T.M. Aathif | Spring Boot | 2025


2. Cross-Origin Resource Sharing (CORS)
CORS is a security mechanism that prevents a frontend (e.g., React on port
3000) from accessing a backend on a different domain (e.g., Spring on port
8080) unless explicitly permitted.
Code Example

3. Content Filtering: @JsonIgnore


This annotation prevents sensitive data from being serialized into the JSON
response sent to the client.
Code Example

M.T.M. Aathif | Spring Boot | 2025


4. XML Support
By default, Spring Boot uses JSON. To enable XML, the jackson-dataformat-
xml dependency must be added to the [Link].
Maven Dependency

Controller Implementation
No code changes are required in the Controller. The format is determined by
the client's Accept header.

• Requesting JSON: Header Accept: application/json


• Requesting XML: Header Accept: application/xml

M.T.M. Aathif | Spring Boot | 2025


Consuming REST Services
in Spring Applications
In a microservices architecture, applications often need to communicate with
external APIs or other internal services. Spring provides several ways to
consume RESTful web services, ranging from traditional synchronous
templates to modern, non-blocking reactive clients and declarative interfaces.

Introduction to Consuming REST Services


Consuming a REST service involves sending an HTTP request (GET, POST, etc.)
to a remote URL, receiving a response (usually JSON or XML), and mapping
that response into Java objects (POJOs) for processing within the local
application logic.
Spring's RestTemplate and WebClient are the traditional tools, while
OpenFeign simplifies REST client creation by abstracting boilerplate code.
Core Requirements:
▪ HTTP Client: A library or framework to handle the network connection.
▪ Message Converter: An engine (like Jackson) to transform JSON into Java
objects.
▪ Error Handling: Logic to manage timeouts, 4xx (client), and 5xx (server)
errors.

Consuming Services with OpenFeign


OpenFeign is a declarative REST client developed by Netflix and now
maintained as part of the Spring Cloud ecosystem. OpenFeign allows
developers to define REST clients using interfaces and annotations, which
eliminates the need to manually write boilerplate code for HTTP requests.
▪ Declarative Nature: Instead of writing boilerplate code to open
connections, the developer simply defines an interface and annotates it.
Spring Cloud provides the implementation at runtime.
▪ Integration: It integrates seamlessly with other Spring Cloud components
like Load Balancers and Circuit Breakers.
▪ Automatic Error Handling: OpenFeign handles common HTTP errors like
4xx and 5xx automatically, making REST client development easier.

M.T.M. Aathif | Spring Boot | 2025


Integrating OpenFeign in a Spring Boot
Application
1. Add OpenFeign Dependency

2. Enable OpenFeign in Spring Boot Application

3. Create a Feign Client Interface

4. Use Feign Client in Service Layer

• @EnableFeignClients enables OpenFeign support in the Spring Boot


application.
• Feign automatically implements the UserClient interface and handles HTTP
requests to the user-service API.

M.T.M. Aathif | Spring Boot | 2025


Consuming Services with RestTemplate
RestTemplate is the traditional, synchronous client provided by Spring.
Although it is currently in "maintenance mode" (with WebClient being the
preferred modern alternative), it remains widely used in millions of legacy and
standard Spring applications.

▪ Synchronous Requests: Blocks the execution until the response is received.


▪ Simple API: Offers methods like getForObject(), postForObject(), put(), and
delete() to handle HTTP requests.
Example: Using RestTemplate to Consume a REST Service

• [Link]() sends a GET request to the specified URL and


maps the response body to the User object.
• The RestTemplate bean is configured in a configuration class and injected
into the service.

M.T.M. Aathif | Spring Boot | 2025


Consuming Services with WebClient
WebClient is a non-blocking, reactive web client introduced in Spring 5 as part
of the Spring WebFlux framework. It is a modern alternative to RestTemplate
and provides asynchronous and reactive support for consuming REST services.
▪ Non-blocking: Allows making asynchronous HTTP requests, improving
scalability.
▪ Reactive: Built for handling a large number of concurrent requests.
▪ Fluent API: Provides a fluent, easy-to-use API for making HTTP requests.
Example: Using WebClient to Consume a REST Service
1. Add WebClient Dependency

2. Configure WebClient Bean

3. Use WebClient in the Service Layer

• bodyToMono([Link]) maps the response body to a Mono of the User


class, which is part of Project Reactor.
• Mono represents a single asynchronous value, providing a reactive way to
consume REST services.
M.T.M. Aathif | Spring Boot | 2025
Additional Important Topics
1. HTTP Interface Clients (Spring 6+)
This is the native Spring alternative to OpenFeign. It allows the definition of an
interface with @HttpExchange annotations, which Spring then implements
using a WebClient or RestTemplate under the hood.
Code Example
Define the Interface:

Create the Proxy Bean:

M.T.M. Aathif | Spring Boot | 2025


2. Error Handling & Response
ErrorHandlerWhen a remote service returns an error (4xx or 5xx), clients must
intercept these to prevent raw exceptions from crashing the local application.
Code Example (RestTemplate)

3. Load Balancing (Spring Cloud)


Load balancing ensures that client requests are distributed across multiple
instances of a service rather than just one.
Code Example
Simply annotate the RestTemplate bean or [Link] with
@LoadBalanced.

M.T.M. Aathif | Spring Boot | 2025


4. Circuit Breakers (Resilience4j)
A circuit breaker monitors failures. If a remote service fails too often, the
circuit "opens," and the client immediately returns a fallback instead of waiting
for a network timeout.
Code Example

5. Timeouts and Retries in WebClient


Setting timeouts prevents the application from hanging on slow network calls,
while retries provide resilience against intermittent "glitches."
Code Example

M.T.M. Aathif | Spring Boot | 2025


Spring Data REST & HAL
Explorer
Spring Data REST is a powerful module that automatically exports Spring Data
repositories as hypermedia-driven RESTful web services. It eliminates the
need to write boilerplate controller code for standard CRUD operations,
allowing focus on core business logic.

Introduction to Spring Data REST & HAL


Explorer
Spring Data REST
Automatic Exposure: It analyzes the domain model and automatically creates
REST endpoints for any repository extending interfaces like JpaRepository or
CrudRepository.
HATEOAS Principles: The generated APIs follow the "Hypermedia as the
Engine of Application State" principle, including navigational links in responses
to help clients discover related resources.
Default Format: It uses HAL (Hypertext Application Language) as the standard
media type for JSON responses.
HAL Explorer
Discovery Tool: An Angular-based web application integrated into Spring Boot
that provides a user-friendly UI to browse, search, and interact with HAL-
compliant REST APIs.
Visual Interface: Instead of using command-line tools like curl, it allows
developers to click through links, view resource details, and perform HTTP
methods (GET, POST, PUT, DELETE) directly in the browser.

M.T.M. Aathif | Spring Boot | 2025


Exploring REST APIs with HAL Explorer
To enable this tool, add the spring-data-rest-hal-explorer dependency to the
[Link]. Once the application is running, the explorer is typically accessible
at the root URL (e.g., [Link]
Core Functionalities
▪ Navigation: The interface displays _links provided by Spring Data REST.
Clicking a link (e.g., /students) navigates to that collection resource.
▪ CRUD Interactions: For each resource, HAL Explorer provides forms to
create new records (POST) or edit existing ones (PUT/PATCH). It
automatically detects field names from the entity's properties.
▪ Search Resources: Custom query methods defined in the repository (e.g.,
findByEmail) are automatically exposed under a /search endpoint, which
can be triggered via the UI.
▪ Pagination & Sorting: The explorer recognizes HATEOAS metadata for
pagination, allowing for easy page switching and column sorting without
manual URL manipulation.

Securing Spring Data REST & HAL Explorer


Since Spring Data REST automatically exposes all public repositories, security
is a critical production requirement to prevent unauthorized data access.
▪ Spring Security Integration: REST endpoints are secured by adding the
spring-boot-starter-security dependency and defining a SecurityFilterChain
bean.
▪ Role-Based Access (RBAC): Access can be restricted based on user roles.
For example, a "STUDENT" might only have GET access, while an "ADMIN"
can perform POST or DELETE operations.
▪ Method-Level Security: Annotations like @PreAuthorize can be placed
directly on repository methods to enforce specific permissions.
▪ Disabling Exposure: If a specific repository or method should not be public,
it can be hidden using @RepositoryRestResource(exported = false).

M.T.M. Aathif | Spring Boot | 2025


Additional Important Topics
1. Projections and Excerpts
Projections allow the creation of client-specific representations of data by
limiting the fields returned in a response.
• Example: An EmployeeExcerpt interface might only return firstName and
jobTitle, hiding sensitive details like salary.

2. Lifecycle Event Hooks


Spring Data REST triggers application events (e.g., BeforeSaveEvent,
AfterDeleteEvent) during the request lifecycle. Developers can create
@Component listeners to inject custom business logic (like logging or
validation) before data is persisted.

3. Customizing Base Path


The root of the REST API can be moved from / to a specific path like /api to
avoid conflicts with static web content.
• Property: [Link]-path=/api.

4. ALPS Metadata
Application-Level Profile Semantics (ALPS) provides an extra layer of metadata
describing the "semantics" of the API, which tools like HAL Explorer use to
generate better documentation and input forms.

M.T.M. Aathif | Spring Boot | 2025


Logging Configurations in
Spring Boot
Introduction to Logging in Spring Boot
Spring Boot uses SLF4J (Simple Logging Facade for Java) as an abstraction
layer for its logging API. This allows developers to write code against a
standard interface while the actual logging implementation can be swapped
without changing the application code.
▪ Default Implementation: Logback is the default logging provider used when
starters are included in the project.
▪ Pre-configuration: Logs are automatically routed to the console by default
at the INFO level, showing details like timestamps, thread names, and log
levels.
▪ Log Levels: Support includes TRACE, DEBUG, INFO, WARN, ERROR, and
FATAL (mapped to ERROR in Logback).

M.T.M. Aathif | Spring Boot | 2025


Logging Configurations for Framework
Code
Framework logging (e.g., Spring, Hibernate, Tomcat) is often noisy. Controlling
these logs is essential to keep production logs clean while allowing deep
debugging during development.
Using [Link]
The [Link].<package-name> property allows for fine-tuning the
verbosity of specific framework components.

Logging Configurations for Application


Code
Isolating application-specific logs from framework noise helps in monitoring
business-critical events.
Package-Level Configuration
Application log levels are typically set per package to manage granularity.

Profile-Based Logging
Different environments (Dev vs. Prod) require different configurations. This can
be achieved using environment-specific properties files like application-
[Link] or [Link].

M.T.M. Aathif | Spring Boot | 2025


Storing Logs into Custom Files and Folders
For persistent storage, logs must be written to the local disk or a centralized
server.
Method 1: Using Properties (Simple)
Two primary properties control file-based logging:
▪ [Link]: Specifies a fixed path and file name.
▪ [Link]: Specifies a directory where [Link] will be created.

Method 2: Using [Link] (Production Level)


For advanced requirements like Log Rotation (splitting files by size or date)
and Retention Policies, a custom configuration file is required in
src/main/resources.

M.T.M. Aathif | Spring Boot | 2025


Additional Best Practices
1. Asynchronous Logging
To prevent logging operations from slowing down the main execution thread,
Asynchronous Appenders can be configured in the XML file. This offloads the
writing of log files to a background thread.

2. Structured Logging (JSON)


Modern log aggregators (ELK, Grafana Loki) prefer machine-readable formats.
Using a JSON layout allows for easier searching and filtering of logs based on
fields like userId or timestamp.

3. Masking Sensitive Data


Production logs must not contain sensitive information such as passwords,
API keys, or Personal Identifiable Information (PII). This is often handled
using custom Logback Converters or filters to redact sensitive strings before
they reach the file.

M.T.M. Aathif | Spring Boot | 2025


Properties Configuration
& Profiles
Introduction to Externalized Properties
Spring Boot loads properties from various sources into the Environment.
Common sources include property files (.properties), YAML files (.yml),
environment variables, and command-line arguments.
Order of Precedence (Highest to Lowest)
If a property exists in multiple sources, the one higher in this list "wins":
▪ Command Line Arguments: e.g., --[Link]=9000.
▪ Java System Properties: e.g., [Link]().
▪ OS Environment Variables: e.g., SPRING_PROFILES_ACTIVE=prod.
▪ Profile-specific Application Properties: application-{profile}.properties
located outside or inside the JAR.
▪ Default Application Properties: [Link] located outside or
inside the JAR.

Relaxed Binding Spring is "relaxed" about names. All the following will map to
the Java variable firstName:
▪ first-name (Kebab-case - Recommended for .properties/.yml)
▪ first_name (Underscore)
▪ FIRST_NAME (Upper case - Recommended for OS Environment Variables)

M.T.M. Aathif | Spring Boot | 2025


Reading Properties in Code
A. Using @Value Annotation
The @Value annotation binds specific properties directly to fields, method
parameters, or constructor arguments within a Spring bean.

Note: If the property is missing and no default is provided, the application will
fail to start.

B. Using Environment Interface


The Environment interface provides programmatic access to properties and
active profiles. It is useful when property keys must be determined
dynamically at runtime.

M.T.M. Aathif | Spring Boot | 2025


C. Using @ConfigurationProperties (Type-Safe)
This is the preferred approach for grouping related properties into a single
Plain Old Java Object (POJO). It supports relaxed binding (e.g., [Link]-
path maps to contextPath) and validation.
Clear Example: Database Configuration First, define your properties in
[Link]:

Then, create the Java Bean:

Implementation: Requires
• @EnableConfigurationProperties([Link]) or
@ConfigurationPropertiesScan in the main application class.

M.T.M. Aathif | Spring Boot | 2025


Profiles in Spring
Profiles provide a way to segregate parts of the application configuration and
make it available only in specific environments.
A. Profile Naming Conventions
Spring Boot automatically loads properties from files following the application-
{profile}.properties or application-{profile}.yml pattern based on the active
profile.
▪ [Link]: Development-specific (e.g., In-memory H2
database).
▪ [Link]: Production-specific (e.g., Real MySQL
database).
B. Activation Approaches
▪ In properties: [Link]=dev inside [Link].
▪ Command Line: java -jar [Link] --[Link]=prod.
▪ Environment Variables: export SPRING_PROFILES_ACTIVE=test.
▪ Programmatically: [Link]("dev") before
running the app.
C. Conditional Bean Creation
The @Profile annotation limits the registration of a @Component or @Bean to
when specific profiles are active.

M.T.M. Aathif | Spring Boot | 2025


Production Best Practices
▪ Externalize Sensitive Data: Never store passwords or API keys in
[Link] inside the JAR. Use OS environment variables or a
Secret Manager.
▪ Use Defaults: Use the colon syntax in @Value (e.g., ${key:default}) to
ensure the application starts even if a property is missing in a new
environment.
▪ Prefer @ConfigurationProperties: For production, type-safe POJOs are
easier to maintain and validate than scattered @Value annotations.
▪ Profile-Specific Overrides: Keep common properties in
[Link] and only put environment-specific overrides in
application-{profile}.properties to minimize duplication.

M.T.M. Aathif | Spring Boot | 2025


Spring Boot Actuator &
Spring Boot Admin
Monitoring is the backbone of production reliability. Spring Boot Actuator
provides built-in, production-ready features that allow for the monitoring and
management of applications, while Spring Boot Admin provides a graphical
interface to visualize this data.

Introduction to Spring Boot Actuator


Actuator is a sub-project of Spring Boot that exposes operational information
about a running application via HTTP or JMX endpoints.
Purpose: It provides "observability"—the ability to understand the internal
state of a system by looking at the data it provides.
Core Dependency:

Deep Dive: Actuator Endpoints


By default, most endpoints are disabled for security reasons. Only /health and
/info are typically visible without further configuration.
Endpoint Description

/health Shows application health information (UP, DOWN, etc.).

Shows various metrics (JVM memory, CPU usage, HTTP


/metrics
requests).

/env Exposes properties from the Spring Environment.

/beans Displays a complete list of all Spring beans in the context.

/loggers Allows viewing and modifying log levels at runtime.

Performs a thread dump for diagnosing performance


/threaddump
bottlenecks.

/heapdump Generates a JVM heap dump for memory leak analysis.

Allows the application to be gracefully shut down (Disabled by


/shutdown
default).
M.T.M. Aathif | Spring Boot | 2025
Implementing & Securing Actuator
A. Exposing Endpoints
Endpoints are controlled via [Link]. It is a production best
practice to expose only what is strictly necessary.

B. Securing with Spring Security


Exposing sensitive data like /env or /heapdump to unauthorized users is a high
security risk. Actuator endpoints should be placed behind authentication.

C. Separate Management Port


For an extra layer of security, the management endpoints can be hosted on a
different port than the main application. This allows firewalling the
management port from external traffic.

M.T.M. Aathif | Spring Boot | 2025


Exploring Data with Spring Boot Admin
Spring Boot Admin (SBA) is a third-party community project that provides a
web-based UI to manage and monitor Spring Boot applications. It consists of a
Server and Clients.
A. Setting up the Admin Server
The server application acts as the dashboard.
1. Dependency: spring-boot-admin-starter-server
2. Activation:

B. Registering Admin Clients


Each application that needs to be monitored must register with the server.
1. Dependency: spring-boot-admin-starter-client
2. Configuration:

M.T.M. Aathif | Spring Boot | 2025


Additional Topics
1. Custom Health Indicators
Standard health checks monitor the disk and database. Custom indicators can
be written to check internal business states (e.g., connectivity to a legacy
mainframe or a third-party API).
Implementation: Implement the HealthIndicator interface and define the logic
in the health() method.
2. Custom Endpoints (@Endpoint)
New management endpoints can be created using the @Endpoint annotation.
These methods support @ReadOperation (GET), @WriteOperation (POST), and
@DeleteOperation (DELETE).
3. Sanitizing Sensitive Data
Sensitive keys in /env (like passwords) are automatically "sanitized" (masked
with ******). This list of keys to mask can be customized using
[Link]-to-sanitize.

M.T.M. Aathif | Spring Boot | 2025



THANK YOU

You might also like