0% found this document useful (0 votes)
19 views

Spring Boot Notes

Spring Boot is an extension of the Spring Framework that simplifies Java application development by eliminating boilerplate configurations and providing features like embedded servers and automatic configuration. It utilizes concepts such as Dependency Injection and Inversion of Control to manage application components efficiently. While it offers rapid application development benefits, it may not be suitable for large-scale applications due to increased deployment file sizes and complexities in converting legacy projects.

Uploaded by

Tanish Tavakal
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)
19 views

Spring Boot Notes

Spring Boot is an extension of the Spring Framework that simplifies Java application development by eliminating boilerplate configurations and providing features like embedded servers and automatic configuration. It utilizes concepts such as Dependency Injection and Inversion of Control to manage application components efficiently. While it offers rapid application development benefits, it may not be suitable for large-scale applications due to increased deployment file sizes and complexities in converting legacy projects.

Uploaded by

Tanish Tavakal
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
You are on page 1/ 35

Spring-boot

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:

●​ Instantiating, configuring, and assembling beans.


●​ Managing bean life cycles.
●​ Handling internationalization (i18n).
●​ Publishing events to registered listeners.
●​ Resource loading (eg: loading files, classpath resources)
●​ Supporting application-layer context like environment variables and profiles.

🔸 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

Eager Initialization​ Yes​ ​ ​ No (Lazy by default)

Internationalization​ Yes​ ​ ​ No

Event Propagation​ Yes​ ​ ​ No

AOP Integration​ Full support​ ​ Limited

Annotation Purpose

@Configuration Marks the class as a source of bean


definitions (Java-based config).

@EnableAutoConfiguration Tells Spring Boot to start auto-configuring


the application based on classpath contents
(e.g., if spring-boot-starter-web is found,
configure a web server).

@ComponentScan Automatically detects and registers


components (like @Controller, @Service,
etc.) in the same package and sub-packages.
Spring Boot Architecture

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 Workflow Architecture

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:

●​ Embedded Application Server


●​ Automatic Configuration
●​ Pre-configured Starters
●​ Ease of Packaging and Distribution
●​ Ease of monitoring through built-in health check endpoint and the ability to customize the
management endpoint.
Basis Spring Spring Boot

Spring framework is a java EE framework Spring Boot framework is mainly


Where it’s used?
that is used to build applications. used to develop REST API’s

The main or primary feature of


the Spring Boot is
Autoconfiguration( Simply
described, Spring Boot
autoconfiguration is a method of
The primary or most important feature of
automatically configuring a
the Spring framework is dependency
Spring application based on the
injection(Dependency Injection (DI) is a
Key feature dependencies found on the
design technique that removes
classpath.)
dependencies from computer code, making
the application easier to maintain and test).
Autoconfiguration can speed up
and simplify development by
removing the need to define
some beans that are part of the
auto-configuration classes.

Spring Boot provides the


Its goal is to make Java EE (Enterprise RAD(Rapid Application
Why it’s used Edition) development easier, allowing Development) feature to the
developers to be more productive. Spring framework for faster
application development.

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.

Deployment To run a Spring application a deployment In Spring Boot there is no need


descriptor descriptor is required. for the Deployment descriptor.

Spring Boot provides support for


In-memory Spring framework does not provide support
the in-memory database such as
database support for the in-memory database.
H2.

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.

In Spring Boot there are default


In the Spring framework, you have to build
Configurations configurations that allow faster
configurations manually.
bootstrapping.

Spring Boot, on the other hand,


can get an application working
with just one dependency. There
Spring Framework requires a number of
Dependencies are several more dependencies
dependencies to create a web app.
required during build time that is
added to the final archive by
default.
HTTP Basic Authentication is for enabling security
confirmations, it indicates that several Spring Boot also requires these
dependencies and configurations need to be dependencies to make it work,
enabled to enable security. Spring requires both the but we only need to define the
HTTP standard spring-security-web and dependency of
Authentication spring-security-config dependencies to set up spring-boot-starter-security as
security in an application. Next, we need to add a this will automatically add all the
class that extends the relevant dependencies to the
WebSecurityConfigurerAdapter and makes use of classpath.
the @EnableWebSecurity annotation.

Testing in Spring Boot is difficult in Testing in Spring Boot is easier


Testing comparison to Spring Boot due to a large due to the reduced amount of
amount of source code. source code.

XML In the Spring framework, XML No need for XML configuration in


Configuration Configuration is required. Spring Boot.

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.

Spring Boot provides build tool


Spring framework does not provide any plugins for Maven and Gradle.
Plugins plugin for maven, Gradle, etc. like Spring The Plugins offer a variety of
Boot. features, including the
packaging of executable jars.
What Is Spring?

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

These modules can drastically reduce the development time of an application.

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.

What Is Spring Boot?

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.

Here are just a few of the features in Spring Boot:

●​ Opinionated ‘starter’ dependencies to simplify the build and application configuration


●​ Embedded server to avoid complexity in application deployment
●​ Metrics, Health check, and externalized configuration
●​ Automatic config for Spring functionality – whenever possible
●​ All other dependencies are added automatically to the final archive during build time

Some of the most commonly used ones are:

●​ spring-boot-starter-data-jpa
●​ spring-boot-starter-security
●​ spring-boot-starter-test
●​ spring-boot-starter-web
●​ spring-boot-starter-thymeleaf

Spring Boot uses only Servlet 3 features to bootstrap an application.


The entry point of a Spring Boot application is the class which is annotated with
@SpringBootApplication:

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.

Core IoC Container, Events, Resources, i18n, Validation, Data Binding,


Type Conversion, SpEL, AOP, AOT.
Testing Mock Objects, TestContext Framework, Spring MVC Test,
WebTestClient.
Data Access Transactions, DAO Support, JDBC, R2DBC, O/R Mapping, XML
Marshalling.
Web Servlet Spring MVC, WebSocket, SockJS, STOMP Messaging.
Web Reactive Spring WebFlux, WebClient, WebSocket, RSocket.
Integration REST Clients, JMS, JCA, JMX, Email, Tasks, Scheduling, Caching,
Observability, JVM Checkpoint Restore.
Languages Kotlin, Groovy, Dynamic Languages.
Appendix Spring properties.

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

Autowiring Dependencies: ​ Wiring allows the Spring container to automatically resolve


dependencies between collaborating beans by inspecting the beans that have been defined.

There are four modes of autowiring a bean using an XML configuration:


●​ No → the default value – this means no autowiring is used for the bean and we have to
explicitly name the dependencies.
●​ byName → autowiring is done based on the name of the property, therefore Spring will look
for a bean with the same name as the property that needs to be set.
●​ byType → similar to the byName autowiring, only based on the type of the property. This
means Spring will look for a bean with the same type of the property to set. If there’s more
than one bean of that type, the framework throws an exception.
●​ Constructor → autowiring is done based on constructor arguments, meaning Spring will
look for beans with the same type as the constructor arguments.

@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:

public class Store {

@Autowired

@Qualifier("item1")

private Item item;

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.

Spring Bean Scopes

There are five scopes defined for Spring Beans.

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.​ Annotation Based Configuration - By using @Service or @Component annotations. Scope


details can be provided with @Scope annotation.
2.​ XML Based Configuration - By creating Spring Configuration XML file to configure the
beans. If you are using Spring MVC framework, the xml based configuration can be loaded
automatically by writing some boiler plate code in web.xml file.
3.​ Java Based Configuration - Starting from Spring 3.0, we can configure Spring beans using
java programs. Some important annotations used for java based configuration are
@Configuration, @ComponentScan and @Bean.

Lifecycle of a Spring Bean:

1.​ Instantiation​
2.​ Populate Properties​

3.​ Set Bean Name / Factory / Context​

4.​ Bean Post Processors​

5.​ Initialization (@PostConstruct or init-method)​

6.​ Ready to use​

7.​ Destruction (@PreDestroy or destroy-method)

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.

Sr.No Terms & Description

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.

Spring Web MVC framework

The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet


that dispatches requests to handlers, with configurable handler mappings, view resolution, locale
and theme resolution as well as support for uploading files. The default handler is based on the
@Controller and @RequestMapping annotations, offering a wide range of flexible handling
methods. With the introduction of Spring 3.0, the @Controller mechanism also allows you to
create RESTful Web sites and applications, through the @PathVariable annotation and other
features
Dispatcher servlet as the front controller.

🧩 Core Framework Annotations


Annotation​ ​ Description
@Component​ ​ Marks a class as a Spring-managed component (generic stereotype).
@Service​ ​ Specialized version of @Component for service-layer classes.
@Repository​ ​ Specialized @Component for DAO classes; supports exception translation.
@Controller​ ​ Indicates a Spring MVC controller class.
@RestController​ Combines @Controller and @ResponseBody for REST APIs.

💉 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.

🌱 Configuration & Bean Management


Annotation​ ​ Description
@Configuration​ Declares a class as a source of bean definitions.
@Bean​​ ​ Declares a bean inside a @Configuration class.
@Import​ ​ Imports additional configuration classes.
@PropertySource​ Loads property files into the Spring Environment.
🌐 Spring MVC / Web Annotations
Annotation​ ​ Description
@RequestMapping​ Maps web requests to handler methods (can specify method, path, etc.).
@GetMapping, @PostMapping, etc.​
Shorthand annotations for HTTP methods.
@PathVariable​Binds ​ URI template variables to method parameters.
@RequestParam​ Binds query parameters to method arguments.
@RequestBody​ Binds the body of a request to a method parameter.
@ResponseBody​ Indicates that a method’s return value is bound to the web response body.
@ModelAttribute​ Binds a method parameter or return value to a model attribute.
@SessionAttributes​ Specifies session-scoped model attributes.
@ExceptionHandler​ Handles specific exceptions thrown by controller methods.

🧵 Aspect-Oriented Programming (AOP)


Annotation​ Description
@Aspect​ Marks a class as an aspect (aspect class contains cross-cutting concerns).
@Before, @After, @Around​
Define advice that runs at different points in the method execution lifecycle.
@Pointcut​ Declares reusable pointcut expressions.

💾 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.
@WebMvcTest​Tests ​ Spring MVC controllers in isolation.
@MockBean​ ​ Adds mocks to the Spring ApplicationContext for testing.

Spring Boot Specific Annotations


Spring Boot builds on Spring and adds auto-configuration and convention-over-configuration
support. Its annotations are higher-level and simplify setup.

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.

Spring security works on the following three core concepts

●​ 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.

2. Advantages of Spring security:

●​ Servlet API integration.


●​ Extensible support for both Authentication and Authorization.
●​ Protection against attacks like session fixation, click jacking.
●​ Spring MVC integration.
●​ Ability to secure application against brute force attacks.
●​ Portability.
●​ Protection against CSRF attacks.
●​ Java configuration support

To enable basic Spring security to J2EE applications, we follow the below 3 steps.

1.​ Add jar files


2.​ Filter declaration to pom.xml
3.​ Java configuration by using SecurityConfiguration class

Spring Security Modules

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.

●​ Core – spring-security-core.jar–This module contains core authentication and


access-control related classes, basic provisioning APIs. This is mandatory for
providing spring security to any J2EE based enterprise application. This module
supports non-web applications, too.
●​ Web – spring-security-web.jar–This module contains filters and web-based
authentication, like access control for URLs in a Servlet environment. This
module is responsible for providing security to your Spring MVC or any other web
application.
●​ Config- spring-security-config.jar–This module used to use the Spring Security
XML name-space. It also supports.
●​ LDAP – Modules supporting the LDAP authentication. We may need this if you
want to have LDAP authentication for our application.
●​ OAuth 2.0 Core – Provides support for the OAuth 2.0 authorization.
●​ OAuth 2.0 Client – Spring Security’s client support for OAuth 2.0 Authorization
Framework and OpenID Connect Core 1.0.

Common technologies used in authentication and authorization systems, especially with


frameworks like Spring Security

Technolo Purpose Stateless Format Security Common Pros Cons


gy Level Use Cases

OAuth2 Authorizati ✅ JSON High (with "Login Widely Needs


on (not HTTPS) with adopted, correct
authn) Google", token-bas setup,
third-part ed, works complex
y app well for flows
access APIs (auth
code,
implicit,
etc.)

OpenID Authenticat ✅ JSON / JWT High Identity in Adds user Depends


Connect ion + web/mobil identity to on
(OIDC) OAuth2 e apps OAuth2, OAuth2;
interopera can be
ble, widely overkill for
supported simple
auth
JWT Token ✅ JSON Medium- Stateless Portable, Can be
format (signed) High auth for self-conta abused if
(signed) APIs, SPAs ined, no not
server revoked/e
session xpired
needed properly

SAML Authenticat ✅ XML High Enterprise Mature, Verbose


ion (SSO) SSO (e.g., widely XML,
Office365, adopted in harder to
Salesforce enterprise debug, not
) s ideal for
SPAs/mobi
le

LDAP User ❌ Binary/Tex Medium Corporate Centralize Harder to


directory + t user d user scale, less
auth managem data, secure
ent supports over the
groups/rol web unless
es combined
with TLS

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

API Key App/service ✅ String Low-Medi External Simple to No


auth um APIs (e.g., use for identity,
Stripe, apps, easy hard to
Firebase) to manage/re
integrate voke
securely

Session- Stateful ❌ Cookie Medium- Traditional Familiar Doesn't


based authenticati High web apps pattern, scale well
on easy with without
server-ren shared/sessi
dered UIs on store

Kerberos Secure ❌ Ticket-bas Very High Windows, Strong Complex


network ed enterprise mutual setup,
auth intranets auth, mostly
avoids Windows/
sending Linux only
passwords

FIDO2 / Passwordles ✅ Public Key Very High Biometric Extremely Hardware/


WebAut s auth login, secure, bio devices
hn hardware- phishing-r needed,
based auth esistant, browser
no compatibil
password ity varies
storage
needed

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 Core starter, including auto-configuration,


logging, and YAML support.

spring-boot-starter-web For building web (RESTful) applications


using Spring MVC.

spring-boot-starter-data-jpa For Spring Data JPA with Hibernate.

spring-boot-starter-security Adds Spring Security.

spring-boot-starter-test Testing libraries like JUnit, Hamcrest, and


Mockito.

spring-boot-starter-thymeleaf For using Thymeleaf templating engine.

spring-boot-starter-actuator For monitoring and managing your


application (e.g., health checks, metrics).

spring-boot-starter-logging Built-in default logging with Logback.

spring-boot-starter-mail For sending emails using JavaMailSender.

spring-boot-starter-aop For aspect-oriented programming with


Spring AOP.

spring-boot-starter-validation For bean validation (JSR-380 / Hibernate


Validator).

spring-boot-starter-batch For batch processing using Spring Batch.

spring-boot-starter-cache Adds support for Spring's caching


abstraction.

spring-boot-starter-amqp For messaging with RabbitMQ.

spring-boot-starter-data-mongodb For MongoDB integration.

spring-boot-starter-data-redis For Redis integration.

spring-boot-starter-oauth2-client For OAuth2 client support.

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:

●​ If spring-boot-starter-web is on the classpath, Spring Boot auto-configures Tomcat as the


web server.
●​ If spring-boot-starter-data-jpa is present, it auto-configures a DataSource,
EntityManagerFactory, etc.

You can override the default behavior by:

●​ Defining your own beans (auto-config uses @ConditionalOnMissingBean)


●​ Using application.properties / application.yml
●​ Using @Conditional annotations in your own configuration classes

You can exclude specific configurations:

@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:

1.​ Loading and initializing servlet classes.​

2.​ Mapping URLs to servlet classes.​

3.​ Managing servlet lifecycle (init(), service(), destroy()).​

4.​ Handling HTTP requests/responses (GET, POST, etc.).​

5.​ Providing infrastructure like:​

a.​ Thread management​

b.​ Session management​

c.​ Security (authentication, authorization)​


🧱 Examples of Servlet Containers
Servlet Container Type Notes

Apache Tomcat Standalone or Embedded Default in Spring Boot

Jetty Standalone or Embedded Lightweight, embeddable

Undertow Embedded High-performance, async server

GlassFish Full Java EE server Includes a servlet container

WildFly Full Java EE server Formerly JBoss AS

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.

Object-Relational Mapping (ORM) in Java is a programming technique used to convert data


between Java objects and relational database tables. ORM frameworks abstract the database
interactions, allowing developers to work with high-level Java objects instead of writing SQL
manually. ORM maps Java classes (objects) to database tables and Java fields to table columns.

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).

📘 Think of it like this:


●​ JPA is like the interface or contract.​

●​ Hibernate is one of the implementations of that contract.


●​ We can use Hibernate XML based mapping as well as JPA annotation based mapping.

Advantages of ORM

●​ No need to write SQL for CRUD operations​

●​ Object-oriented approach​

●​ Database independence​

●​ Easier maintenance and refactoring


💡 Why Use JPA Over Hibernate Directly?
Reason Explanation

Portability JPA code can run on any JPA provider (e.g., EclipseLink, OpenJPA), not just
Hibernate.

Standardization JPA is a Java EE / Jakarta EE standard, supported by many tools and


vendors.

Cleaner API Encourages cleaner design and decouples your app from a specific ORM
provider.

🧩 Hibernate-Specific Features (Not in JPA)


JPA gives you the core features, but Hibernate adds extra power:

Hibernate Feature Not in JPA

Caching strategies (2nd-level cache) ✅


Hibernate-specific query options ✅
Interceptors, filters ✅
Native ID generation strategies ✅
Statistics and monitoring ✅
How Hibernate Manages Transactions

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.

Key Concepts in Hibernate Transaction Management

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.

Relationship Type Description JPA Annotation

One-to-One One entity is related to one @OneToOne


other entity

One-to-Many One entity is related to many @OneToMany


entities

Many-to-One Many entities relate to one @ManyToOne


entity

Many-to-Many Many-to-many relationship @ManyToMany


between entities

1. One-to-One Example

🔹 Entities: User ↔ Profile


@Entity @Entity
public class User { public class Profile {
@Id @GeneratedValue @Id @GeneratedValue
private Long id; private Long id;
private String name; private String bio;

@OneToOne(mappedBy = "user", cascade = @OneToOne


CascadeType.ALL) @JoinColumn(name = "user_id")
private Profile profile; private User user;

// getters and setters // getters and setters


} }
2. One-to-Many / Many-to-One Example

🔹 Entities: Author ↔ Book


@Entity @Entity
public class Author { public class Book {
@Id @GeneratedValue @Id @GeneratedValue
private Long id; private Long id;
private String name; private String title;

@OneToMany(mappedBy = "author", cascade = @ManyToOne


CascadeType.ALL) @JoinColumn(name = "author_id")
private List<Book> books = new ArrayList<>(); private Author author;

// getters and setters // getters and setters


} }

3. Many-to-Many Example

🔹 Entities: Student ↔ Course


@Entity @Entity
public class Student { public class Course {
@Id @GeneratedValue @Id @GeneratedValue
private Long id; private Long id;
private String name; private String title;

@ManyToMany @ManyToMany(mappedBy = "courses")


@JoinTable( private List<Student> students = new
name = "student_course", ArrayList<>();
joinColumns = @JoinColumn(name =
"student_id"), // getters and setters
inverseJoinColumns = @JoinColumn(name = }
"course_id")
)
private List<Course> courses = new
ArrayList<>();

// getters and setters


}

🔁 EAGER vs LAZY Loading


JPA allows you to define how related entities are fetched from the database

Fetch Type Description

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:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection

Fix:

●​ Use a transactional service layer (@Transactional) to manage session scope.


●​ Or manually initialize with Hibernate:​
​ Hibernate.initialize(author.getBooks());
📦 Final Notes
●​ Use @JsonIgnore on bidirectional relationships to prevent infinite recursion in JSON
responses (e.g., with Spring Boot + Jackson).
●​ Prefer LAZY loading unless you know you always need related entities.
●​ Keep relationships bidirectional only if truly needed (to avoid complexity).

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:

// Creating a new object in the transient state

Employee employee = new Employee();

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.

1.​ Transient-Persistent State

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.

2.​ Persistent-Detached State

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:

// Creating a new object in the Transient-Persistent state

Employee employee = new Employee();

employee.setName("John");

employee.setAge(30);

// Associating the object with a Hibernate session

Session session = HibernateUtil.getSessionFactory().openSession();

session.beginTransaction();

session.save(employee);

Persistent Code Example:

// Loading an existing object into a Hibernate session

Session session = HibernateUtil.getSessionFactory().openSession();

Employee employee = session.get(Employee.class, 1L);

// Modifying the object in the Persistent-Detached state

employee.setName("Alice");

// Persisting the changes to the database

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:

// Loading an existing object into a Hibernate session

Session session = HibernateUtil.getSessionFactory().openSession();

Employee employee = session.get(Employee.class, 1L);

// Detaching the object from the Hibernate session

session.evict(employee);

// Modifying the object in the Detached state

employee.setAge(35);

// Re-associating the object with a Hibernate session

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:

// Loading an existing object into a Hibernate session

Session session = HibernateUtil.getSessionFactory().openSession();

Employee employee = session.get(Employee.class, 1L);

// 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:

// Creating a new object in the transient state

Employee employee = new Employee();

employee.setName("John");

employee.setAge(30);

// Associating the object with a Hibernate session and entering the Persistent state

Session session = HibernateUtil.getSessionFactory().openSession();

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

Session session = HibernateUtil.getSessionFactory().openSession();

Employee employee = session.get(Employee.class, 1L);

// 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

Session session = HibernateUtil.getSessionFactory().openSession();

Employee employee = session.get(Employee.class, 1L);

// Evicting the object from the session and entering the Detached state

session.evict(employee);

// Modifying the object in the Detached state

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

Session session = HibernateUtil.getSessionFactory().openSession();

Employee employee = session.get(Employee.class, 1L);

// Deleting the object from the database and entering the Removed state

session.beginTransaction();

session.delete(employee);
Microservices :

Spring Cloud Components

1. Spring Cloud Gateway

●​ 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

●​ Provides centralized configuration management.​

●​ Externalizes application properties for all environments (dev, QA, prod).​

●​ Works with Git, file system, or Vault to manage configuration files.​

3. Spring Cloud Circuit Breaker

●​ Implements circuit breaker patterns (like Resilience4j or Hystrix).​

●​ Prevents cascading failures in microservices by stopping calls to a failed service.​

●​ Helps maintain system resilience and availability.​

4. Spring Cloud OpenFeign

●​ A declarative REST client for calling other microservices.​

●​ Simplifies HTTP calls between services by using Java interfaces and annotations.​

5. Sleuth

●​ Adds distributed tracing support.​

●​ Helps track request flow across microservices with trace IDs and span IDs.​

●​ Integrates with tools like Zipkin or OpenTelemetry.​

6. Eureka

●​ A service discovery tool (Eureka Server and Eureka Client).​

●​ Services register themselves and discover other services dynamically.​

●​ Avoids hard-coding service URLs and supports load balancing with Ribbon.​

You might also like