Spring Boot Notes
Spring Boot Notes
Spring Core, the base of the Spring Framework, provides a model for configuring Java applications.
Key concepts include:
Beans (Java objects managed by Spring),
Inversion of Control (IoC) (Spring managing bean lifecycles and dependencies),
Dependency Injection (DI) (Spring providing bean dependencies).
The Spring container (specifically an ApplicationContext) creates and manages these beans. Spring
also offers Aspect-Oriented Programming (AOP) for handling cross-cutting concerns, an event
model for decoupled communication using ApplicationEvent and listeners, abstractions for Data
Access and Transactions, and utilities for Task Execution and Scheduling.
Features
● Create stand-alone Spring applications
● Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
● Provide opinionated 'starter' dependencies to simplify your build configuration
● Automatically configure Spring and 3rd party libraries whenever possible
● Provide production-ready features such as metrics, health checks, and externalized
configuration
● Absolutely no code generation and no requirement for XML configuration
In Spring Framework ApplicationContext is a Spring container. It is responsible for:
🔸 Common Implementations
● ClassPathXmlApplicationContext – Loads context definition from an XML file in the
classpath.
● FileSystemXmlApplicationContext – Loads context from an XML file in the file system.
● AnnotationConfigApplicationContext – Used for Java-based configuration.
🔹 ApplicationContext vs BeanFactory
Feature ApplicationContext BeanFactory
Internationalization Yes No
Annotation Purpose
Spring Boot is used to auto-configure the application context and set empty properties.
Presentation Layer: A JSON structure is made up of viewpoints. A front layer is what is seen from the
outside and a back layer is where the structure is built from viewpoints. It interprets JSON and
handles authentication and HTTP requests. After authentication, it enters the business layer for
further processing.
Business Layer: As part of business logic, it manages all of the business decisions and performs the
business validation and consent. For example, only admins may modify the customer’s account.
Persistence Layer: All of the storage logic in this program, including database questions, is
accounted for in this portion of code. It also translates between database rows and company items.
Database Layer: The structure is constructed in this way: The HTTP request or internet requests are
handled by the Controllers from the demonstration layer, the providers control the company logic,
as well as also the repositories preserve persistence (storage logic). Each provider, service, and
repository may be controlled by a single Controller. There are many repositories, which may be
managed by many repositories, and databases may be managed by many databases
Spring Boot relies heavily on the Spring framework, which means that it integrates almost all of the
features and modules of Spring-like Spring MVC, Spring Core, and so on, but there is no demand for
your DAO and DAOImpl classes.
Explanations:
1. Validator classes, view classes, and utility classes have been defined.
2. Spring Boot employs the same modules as Spring-like Spring MVC, Spring Data, and so on,
but it has a different architecture. Spring Boot is the same as Spring MVC, but the one
difference is that no DAO and DAOImpl classes are required.
3. Temporarily blocks an operation in order to create a data access layer and perform CRUD
operations.
4. The client handles the HTTP requests (PUT or GET).
5. The controller receives the request, and it handles it. Then, it passes the request to the
service logic if necessary.
6. All business logic is implemented in the service layer. It performs the logic on the data that
is mapped to JPA using model classes.
7. An error is not reported to the user when a JSP page is returned to the application.
Advantages
1. Spring Boot allows for quick and easy development of spring-based applications in Java or
Groovy.
2. Spring Boot optimizes for reduced time. It reduces the time spent developing and
increasing productivity.
3. By reducing all the manual labour involved in writing annotations, boilerplate codes and
XML configurations, it also helps in reducing the risk of errors.
4. The Spring Boot Application with Spring Ecosystem, which includes Spring Security, Spring
Data, Spring JDBC and Spring ORM, is now easy to integrate with Spring.
5. It would also be easier for developers to follow the ‘Opinionated Defaults Configuration’
6. Development Web apps can be tested using Embedded HTTP servers such as Jetty, Tomcat,
and also conveniently rely on them.
7. The Spring Boot CLI is accessible through the Command Line Interface, which has been and
is being developed and tested in Spring Boot applications written in Java or Groovy.
8. Spring Boot can be built with the aid of tools like Gradle and Maven, as well as the jBOSS.
Alongside, it provides a lot of plugins that make effortless development and testing of
Spring Boot applications possible.
9. Working with embedded and memory databases is extremely convenient and easily
accomplished with the plugin.
Disadvantage
1. There is no problem with converting legacy or existing Spring Framework projects to Spring
Boot applications, however, the time involved in the process is critical.
2. The size of the application deployment file is increased because of the high number of
unused dependencies caused by Spring Boot.
3. Becoming a Spring Boot application requires the time-consuming and complicated process
of converting a legacy Spring project to a Spring Boot one.
4. Many developers argue that Spring Boot is not suitable for building large-scale applications
because it is unsuitable for working with microservices.
5. Spring Boot works well with small applications, as it can be deployed directly into Docker
containers. In a large and complex application, I’d rather not use Spring Boot.
Why Spring
Spring Boot provides a number of features that make it easier to create a Spring-based application,
including:
Type of
Spring framework helps to create a loosely Spring Boot helps to create a
Application
coupled application. stand-alone application.
Development
In the Spring framework to test the Spring Spring Boot offers built-in or
Servers
Project, we need to set up the servers embedded servers such as
dependency
explicitly. Tomcat and jetty.
Spring framework requires too many lines You avoid boilerplate code which
Boilerplate code of code (boilerplate code) even for minimal reduces time and increases
tasks. productivity.
Spring framework does not provide any CLI Spring Boot provides a CLI tool
CLI Tools tool for developing and testing for developing and testing
applications. Spring Boot applications.
Simply put, the Spring framework provides comprehensive infrastructure support for developing
Java applications.
It’s packed with some nice features like Dependency Injection, and out of the box modules like:
● Spring JDBC
● Spring MVC
● Spring Security
● Spring AOP
● Spring ORM
● Spring Test
For example, in the early days of Java web development, we needed to write a lot of boilerplate code
to insert a record into a data source. By using the JDBCTemplate of the Spring JDBC module, we can
reduce it to a few lines of code with only a few configurations.
Spring Boot is basically an extension of the Spring framework, which eliminates the boilerplate
configurations required for setting up a Spring application.
It takes an opinionated view of the Spring platform, which paves the way for a faster and more
efficient development ecosystem.
● spring-boot-starter-data-jpa
● spring-boot-starter-security
● spring-boot-starter-test
● spring-boot-starter-web
● spring-boot-starter-thymeleaf
By default, Spring Boot uses an embedded container to run the application. In this case, Spring Boot
uses the public static void main entry point to launch an embedded web server.
It also takes care of the binding of the Servlet, Filter, and ServletContextInitializer beans from the
application context to the embedded servlet container.
Another feature of Spring Boot is that it automatically scans all the classes in the same package or
sub packages of the Main-class for components.
Configuration:
Spring Core Configuration is the process of configuring the Spring Framework, which involves
specifying the various configuration details required for an application to function properly. This
can include setting up beans, specifying bean dependencies, configuring aspect-oriented
programming (AOP) aspects, and more. Configuration can be done through Java code, XML files, or
using annotations in the code.
Dependency Injection: Spring Boot uses the Spring Framework's Inversion of Control (IoC)
container to manage objects and their dependencies. The IoC container is responsible for creating
objects, wiring them together, and managing their lifecycle. When an object is created, its
dependencies are also created and injected into the object. Transfers the control of objects or
portions of a program to a container or framework.
Types:
● Constructor Injection
● Setter Injection / Property Injection
● Interface Injection
● Field Injection -> @Autowired
Spring IOC:
Inversion of Control (IoC) is a design pattern that is often used in conjunction with the Dependency
Injection (DI) pattern. The basic idea behind IoC is to invert the flow of control in a program, so that
instead of the program controlling the flow of logic and the creation of objects, the objects
themselves control the flow of logic and the creation of other objects.
Inversion of Control is a principle based on which, Dependency Injection is made. Also, as the name
suggests, Inversion of Control is basically used to invert different kinds of additional
responsibilities of a class rather than the main responsibility.
If I have to explain you in simpler terms, then consider an example, wherein you have the ability to
cook. According to the IoC principle, you can invert the control, so instead of you cooking food, you
can just directly order from outside, wherein you receive food at your doorstep. Thus the process of
food delivered to you at your doorstep is called the Inversion of Control.
You do not have to cook yourself, instead, you can order the food and let a delivery executive, deliver
the food for you. In this way, you do not have to take care of the additional responsibilities and just
focus on the main work.
Spring is a popular Java framework that uses IoC and DI to provide a more flexible, modular
approach to software development. ApplicationContext represents the IoC container
@Bean(autowire = Autowire.BY_TYPE)
public class Store {
private Item item;
public setItem(Item item) {
this.item = item;
}
}
We can also inject beans using the @Autowired annotation for autowiring by type:
public class Store {
@Autowired
private Item item;
}
If there’s more than one bean of the same type, we can use the @Qualifier annotation to reference a
bean by name:
@Autowired
@Qualifier("item1")
Spring Bean:
Spring Bean is nothing special, any object in the Spring framework that we initialize through Spring
container is called Spring Bean. Any normal Java POJO class can be a Spring Bean if it’s configured to
be initialized via container by providing configuration metadata information.
1. singleton - Only one instance of the bean will be created for each container. This is the
default scope for the spring beans. While using this scope, make sure bean doesn’t have
shared instance variables otherwise it might lead to data inconsistency issues.
2. prototype - A new instance will be created every time the bean is requested.
3. request - This is same as prototype scope, however it’s meant to be used for web
applications. A new instance of the bean will be created for each HTTP request.
4. session - A new bean will be created for each HTTP session by the container.
5. global-session - This is used to create global session beans for Portlet applications.
6. Application - One bean per ServletContext. Shared across the entire web application.
7. websocket One bean per WebSocket session. For WebSocket-based applications.
The last four scopes mentioned, request, session, application and websocket, are only available in a
web-aware application.
Spring Framework is extendable and we can create our own scopes too. However, most of the times
we are good with the scopes provided by the framework.
Spring Bean Configuration:
Spring Framework provides three ways to configure beans to be used in the application.
1. Instantiation
2. Populate Properties
Spring AOP: Spring AOP (Aspect-Oriented Programming) is a feature of the Spring Framework
that allows developers to define certain behaviors (i.e., "aspects") that cut across multiple
classes, such as logging or transaction management. These behaviors, which are called "advices,"
can be applied to specific "join points" (i.e., points in the execution of a program) in the
application, using "pointcuts" to determine where the advices should be applied.
Spring AOP allows developers to separate the implementation of these cross-cutting concerns
from the business logic of the application, making the code more modular and easier to
understand. This can also make the application more flexible, since the same advices can be
applied to different parts of the code without having to duplicate the code for the advices
themselves.
Aspect This is a module which has a set of APIs providing cross-cutting requirements.
For example, a logging module would be called AOP aspect for logging. An
application can have any number of aspects depending on the requirement.
Join point This represents a point in your application where you can plug-in the AOP
aspect. You can also say, it is the actual place in the application where an action
will be taken using Spring AOP framework.
Advice This is the actual action to be taken either before or after the method execution.
This is an actual piece of code that is invoked during the program execution by
Spring AOP framework.
Pointcut This is a set of one or more join points where an advice should be executed. You
can specify pointcuts using expressions or patterns as we will see in our AOP
examples.
Introduction An introduction allows you to add new methods or attributes to the existing
classes.
Target object The object being advised by one or more aspects. This object will always be a
proxied object, also referred to as the advised object.
Weaving Weaving is the process of linking aspects with other application types or objects
to create an advised object. This can be done at compile time, load time, or at
runtime.
Types of Advice:
before Run advice before the a method execution.
after
Run advice after the method execution, regardless of its outcome.
after-returning Run advice after the a method execution only if method completes
successfully.
after-throwing Run advice after the a method execution only if method exits by throwing an
exception.
around Run advice before and after the advised method is invoked.
💉 Dependency Injection
Annotation Description
@Autowired Injects dependencies by type (can be used on constructors, fields, or setters).
@Qualifier Disambiguates which bean to inject when multiple candidates exist.
@Inject Java standard (JSR-330) alternative to @Autowired.
@Value Injects values from properties or expressions (SpEL).
@Primary Marks a bean as the default when multiple candidates exist.
💾 Transaction Management
Annotation Description
@Transactional Declares a transactional context on a method or class.
🧪 Testing Support
Annotation Description
@SpringBootTest Boots the full application context for integration testing.
@WebMvcTestTests Spring MVC controllers in isolation.
@MockBean Adds mocks to the Spring ApplicationContext for testing.
Annotation Description
@SpringBootApplication → @Configuration,@EnableAutoConfiguration, and @ComponentScan.
@EnableAutoConfiguration Automatically configures Spring application based on classpath
contents.
@ComponentScan → Scans for components in specified packages (included in
@SpringBootApplication).
@ConfigurationProperties Binds external configuration to a Java bean.
@RestController Combines @Controller and @ResponseBody.
@SpringBootTest Bootstraps the full application context for tests.
@EnableConfigurationProperties Enables @ConfigurationProperties classes.
@DataJpaTest, @WebMvcTest, @MockBean Specialized test annotations.
Spring security
In simple words, Spring security provides authentication and authorization to our application
using simple servlet filters. Web applications are susceptible to security threats and attacks, as
they are accessible by anyone uses the internet. There may exist some REST endpoints having
restricted access to specific users, for example, updating records or admin related operations.
Spring Security is a security framework that secures J2EE-based enterprise applications, by
providing powerful, customizable security features like authentication and authorization. It is the
de facto standard for securing Spring-based applications.
● Authentication
● Authorization
● Password Storage
● Servlet Filters
1.1. Authentication: Used to verify if a user using an application by providing valid credentials
used to verify who you are! Authentication is establishing identity of a principal (user, system,
that can perform an action in an application).
1.2. Authorization: This is besides the authentication. For a simple application, authenticating
user might be enough, but let’s think about a big enterprise application.
● A normal employee (e.g. Call center agent) may have only limited permission to
carry out certain operations.We don’t want to allow this employee to perform
other operations
● Our back-end product manager allowed to work only on the products. We don’t
allow product manager to change customer information or order information.
● Ecommerce manager can work on both customer and order information, but they
can’t change product information.
● System admin can perform all the operations.
With simple authentication, we can’t restrict logged in user as we don’t have information about
user privileges or permissions. Authorization helps to provide this information before the user
tries to access a resource. It is a process of access control, deciding whether it allows a principal to
perform an action (access-control → admin, user, leader, manager, contractor, anonymous etc) or
not.
1.3 Password Storage
Making sure that our passwords are secure and difficult to hack is another primary goal of any
security framework. Spring Security’s PasswordEncoder interface perform one way transform for
the password (We can’t decrypt the password).Spring Security provides several PasswordEncoder,
Here is a list for your reference:
1. BCryptPasswordEncoder.
2. Argon2PasswordEncoder.
3. Pbkdf2PasswordEncoder
4. SCryptPasswordEncoder.
[pullquote align=”normal”] Read Password encoding in spring security to get more details about
how the password encoder works with Spring Security [/pullquote]
1.4 Servlet Filters: Spring security uses the Java servlet filters to start the security check for our
web application.
To enable basic Spring security to J2EE applications, we follow the below 3 steps.
In Spring Security, the Security module comprises separate jar files based on its functionality. The
primary use is to allow the user to integrate according to the requirements. To include minimal
spring security for your Maven project, include below dependencies in your pom.xml.
Basic Simple login ❌ Base64 Low Test apps, Very Not secure
Auth internal simple to without
APIs implemen HTTPS,
t credential
s sent with
every
request
Multi-Fa Auth ❌ Varies Very High Any secure Adds extra Inconveni
ctor hardening login layer of ent for
Auth security some
(MFA) users,
implemen
Spring Boot Starters:
Are a set of convenient dependency descriptors provided by Spring Boot to simplify the process of
setting up a new Spring application. They bundle commonly used dependencies into a single
starter package, so you don't need to specify individual libraries manually.
Starter Description
Spring-boot-starter-oauth2-
resource-server For OAuth2 resource server support.
Auto-configuration in Spring Boot is one of its most powerful features. It simplifies application
setup by automatically configuring Spring beans based on the dependencies on the classpath and
the defined application properties.
🔍 What Is Auto-configuration?
Spring Boot’s auto-configuration attempts to automatically configure your Spring application
based on the jars you have in your classpath. It helps you avoid writing a lot of boilerplate
configuration.
For example:
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
Servlet Container
A Servlet Container (also known as a Servlet Engine) is a part of a web server or application server
that:
Manages the lifecycle of Java Servlets, handles HTTP requests and responses, and
provides web-related services like security, concurrency, and session management.
🔧 What It Does
The servlet container is responsible for:
Spring Boot Actuator: It is a powerful feature of Spring Boot that helps you monitor and
manage your application in production. It provides a set of built-in endpoints that give insights
into your application's internals, such as health, metrics, environment properties, and more.
JPA A standard/specification in Java for ORM (defines how to map Java objects to
relational databases). Hibernate, EclipseLink, and others implement it.
Hibernate A framework/tool that implements JPA (plus adds more features beyond JPA).
Advantages of ORM
● Object-oriented approach
● Database independence
Portability JPA code can run on any JPA provider (e.g., EclipseLink, OpenJPA), not just
Hibernate.
Cleaner API Encourages cleaner design and decouples your app from a specific ORM
provider.
Hibernate uses the Java Transaction API (JTA) and JDBC to manage transactions. Transactions in
Hibernate are usually managed through the org.hibernate.Transaction interface, which provides
methods to control the transaction lifecycle.
1. Session: The Session interface in Hibernate represents a single-threaded unit of work. It
wraps a JDBC connection and is used to interact with the database.
2. Transaction: The Transaction interface represents a single transaction. Transactions are
started, committed, or rolled back using this interface.
Transaction Lifecycle
1. Begin Transaction: A transaction is initiated using the beginTransaction method of the
Session interface.
2. Commit Transaction: If all operations within the transaction are successful, the
transaction is committed using the commit method of the Transaction interface.
3. Rollback Transaction: If an error occurs, the transaction is rolled back using the rollback
method of the Transaction interface.
Relationships:
Using hibernate, if we want to have relationship between two entities, there must exist a foreign
key relationship between the tables, we call it as Referential integrity. The main advantage of
having relationship between objects is, we can do operation on one object, and the same operation
can transfer onto the other object in the database.
1. One-to-One Example
3. Many-to-Many Example
LAZY (default for @OneToMany, Loads the relationship only when accessed.
@ManyToMany)
EAGER (default for @OneToOne, Loads the relationship immediately with the
@ManyToOne) parent entity.
💡 Practical Tip: Why Use LAZY?
● Reduces performance overhead (especially for large collections).
● Gives control over when relationships are loaded.
❗ Beware of LazyInitializationException
If you access a lazy-loaded collection outside of the transaction (e.g., after closing the session),
you'll get:
Fix:
Hibernate Lifecycle
The Hibernate life cycle consists of four main states: Transient, Persistent, Detached, and
Removed. Each of these states represents a specific state of an object in the Hibernate framework.
Transient State
When an object is created using the “new” keyword, it is in the transient state. The object is not
associated with any Hibernate session, and no database operations are performed on it. The
object is simply a plain Java object (POJO) that is not yet persisted in the database.
Code Example:
employee.setName("John");
employee.setAge(30);
Persistent State: When an object is associated with a Hibernate session, it enters the
persistent state. In this state, the object is associated with a specific Hibernate session and is
actively managed by Hibernate. Any changes made to the object will be tracked by Hibernate and
will be persisted to the database when the session is flushed.
There are two sub-states of the persistent state: Transient-Persistent and Persistent-Detached.
When an object is first associated with a Hibernate session, it is in the Transient-Persistent state.
This means that the object is newly created, and its state is not yet synchronized with the
database. Any changes made to the object in this state will be persisted to the database when the
session is flushed.
On the other hand, when an object is already in the database and is loaded into a Hibernate
session, it is in the Persistent-Detached state. Any changes made to the object in this state will
also be tracked by Hibernate and will be persisted to the database when the session is flushed.
Transient Code Example:
employee.setName("John");
employee.setAge(30);
session.beginTransaction();
session.save(employee);
employee.setName("Alice");
session.beginTransaction();
session.update(employee);
Detached State
When a persistent object is no longer associated with a Hibernate session, it enters the detached
state. This means that the object is no longer actively managed by Hibernate, and any changes
made to it will not be persisted to the database. However, the object is still a valid Java object and
can be re-associated with a Hibernate session in the future.
Code Example:
session.evict(employee);
employee.setAge(35);
session.beginTransaction();
session.update(employee);
Removed State
When an object is deleted from the database, it enters the removed state. This means that the
object is no longer associated with the database, and any attempts to modify it or re-associate it
with a Hibernate session will result in an exception.
Code Example:
// Deleting the object from the database and entering the Removed state
session.beginTransaction();
session.delete(employee);
Hibernate Life Cycle Transitions
Now that we have covered all the Hibernate life cycle states, let’s take a look at the transitions that
occur between them.
Transient -> Persistent: The transient object becomes persistent when it is associated with a
Hibernate session using the “save()” or “persist()” methods.
Code Example:
employee.setName("John");
employee.setAge(30);
// Associating the object with a Hibernate session and entering the Persistent state
session.beginTransaction();
session.save(employee);
Persistent -> Detached: A persistent object becomes detached when the Hibernate session
is closed, or the object is explicitly evicted from the session.
Code Example:
// Loading an existing object into a Hibernate session and entering the Persistent state
// Evicting the object from the session and entering the Detached state
session.evict(employee);
Detached -> Persistent: A detached object becomes persistent when it is re-associated with
a Hibernate session using the “update()” or “merge()” methods.
Code Example:
// Loading an existing object into a Hibernate session and entering the Persistent state
// Evicting the object from the session and entering the Detached state
session.evict(employee);
employee.setAge(35);
// Re-associating the object with a Hibernate session and entering the Persistent state
session.beginTransaction();
session.update(employee);
Persistent -> Removed: A persistent object becomes removed when it is deleted from the
database using the “delete()” method.
Code Example:
// Loading an existing object into a Hibernate session and entering the Persistent state
// Deleting the object from the database and entering the Removed state
session.beginTransaction();
session.delete(employee);
Microservices :
● A reactive API Gateway that handles & Acts as a single entry point for all client requests:
1. Routing requests to microservices
2. Load balancing
3. Path rewriting
4. Rate limiting
2. Cloud Config
● Simplifies HTTP calls between services by using Java interfaces and annotations.
5. Sleuth
● Helps track request flow across microservices with trace IDs and span IDs.
6. Eureka
● Avoids hard-coding service URLs and supports load balancing with Ribbon.