Spring Framework:
- It is an open source framework that provide support to develop both standalone and
enterprise applications.
- Spring framework was initially written by Rod Johnson and was initial released under
the Apache 2.0 license in June 2003, but its first product version 1.0 released in 2004.
- Spring framework targets to make J2EE development easier to use and promotes good
programming practices by enabling a POJO-based programming model
Spring Container (IoC Container):
- The core component(heart) of the Spring Framework is the Inversion of Control (IOC)
container.
- The container will create the objects, wire them together, configure them, and manage
their complete life cycle from creation till destruction.
- The container gets its instructions on what objects to instantiate, configure, and
assemble by reading the configuration file. The configuration file can be an XML
configuration file, a Java Configuration file, or an Annotation configuration file.
Resposbilities:
o Mange Bean objects
o Manage the life cycle of bean objects and their dependencies
o Dependency Injection (DI)
o Aspect Oriented Programming (AoP)
o Transaction management etc.
o
Types:
1. BeanFactory Container (old)
• This is the simplest container providing the basic support for DI and is
defined by the [Link] interface.
2. ApplicationContext Container (New)
• This is an advanced container built on top of the BeanFactory.
• It includes all the features of BeanFactory and adds extra functionalities
such as internationalization, event propagation, and integration with other
Spring modules.
• The container is defined by the [Link]
interface.
• In this, beans are created and configured at startup.
The diagram below demonstrates how the Container makes use of Configuration metadata
and Java POJO classes to manage beans.
Working of IoC Container
• The container reads configuration metadata (XML, Java annotations, or Java-based
configuration) to understand how beans should be creates and wired together.
• It uses Dependency Injection (DI) to inject dependencies into beans at runtime.
• The container manages the entire lifecycle of beans, from instantiation to destruction.
Example: (Using XML Configuration File)
- We use [Link] as POJO Class
- We use [Link] as XML configuration file.
- We use [Link] as main file to run the program.
Output: When run [Link]
Example: (Using Java Configuration File)
- We use [Link] as POJO Class
- We use [Link] as java configuration file. (you can change name of it.)
- We use [Link] as main file to run the program.
Output:
Output:
See both Xml Configuration file and java configuration file and observe the difference :
Example: (Using Annotation based Configuration File)
Note: when you are using annotation, you also have to create an Xml configuration file or a Java
Configuration file. Suppose we are creating an Xml configuration file.
Spring Bean Lie Cycle:
Dependency Injection:
Dependency injection is used to avoid hard coding. If we are not using
dependency injection then classes will be dependent on each other.
Here object of Address class is printed.
Using Constructor metod:
Autowiring:
XML Based Autowiring - byName
XML Based Autowiring – byType
It use setter method internally.
XML Based Autowiring – constructor
Annotationbased Autowiring
---------
No need of getter and setter method for address.
So, Design Patterns are the predefined ways or reusable solutions by which we can solve the common
problems (like organizing the code, handling the user interaction) that occur during software
development. So, Design pattern makes the software development easy.
Bean:
- A bean is an object of Java Bean Class.
- A bean is an object that is instantiated, assembled, and otherwise managed by a
Spring IoC container.
- These beans are created with the configuration file that you supply to the container.
For example, in the form of XML <bean/> definitions, which you have seen already.
[Link]. Attribute used in <bean> tag
class
1
This attribute is mandatory and specifies the bean class to be used to create the bean.
name
2 This attribute specifies the bean identifier uniquely. In XMLbased configuration metadata, you use
the id and/or name attributes to specify the bean identifier(s).
scope
3 This attribute specifies the scope of the objects created from a particular bean definition and it will
be discussed in bean scopes chapter.
constructor-arg
4
This is used to inject the dependencies and will be discussed in subsequent chapters.
properties
5
This is used to inject the dependencies and will be discussed in subsequent chapters.
autowiring mode
6
This is used to inject the dependencies and will be discussed in subsequent chapters.
Bean Scopes :
- It refers to the lifecycle of a Bean, which means when the object of a Bean is instantiated, how
long it lives, and how many objects are created for that Bean throughout its lifetime.
- Basically, it controls the instance creation of the bean, and it is managed by the Spring
container.
When defining a <bean> you have the option of declaring a scope for that bean. For example,
to force Spring to produce a new bean instance each time one is needed, you should declare
the bean's scope attribute to be prototype. Similarly, if you want Spring to return the same
bean instance each time one is needed, you should declare the bean's scope attribute to be
singleton.
Bean Scopes in Spring
The Spring Framework supports the following five scopes, three of which are available only if you use
a web-aware ApplicationContext.
1. Singleton: Only one instance will be created for a single bean definition per Spring IoC
container, and the same object will be shared for each request made for that bean.
2. Prototype: A new instance will be created for a single bean definition every time a request is
made for that bean.
3. Request: A new instance will be created for a single bean definition every time an HTTP
request is made for that bean. But only valid in the context of a web-aware Spring
ApplicationContext.
4. Session: Scopes a single bean definition to the lifecycle of an HTTP Session. But only valid in
the context of a web-aware Spring ApplicationContext.
5. Global-Session: Scopes a single bean definition to the lifecycle of a global HTTP Session. It is
also only valid in the context of a web-aware Spring ApplicationContext.
For example:
The default scope is always singleton. However, when you need one and only one instance of a bean,
you can set the scope property to singleton in the bean configuration file, as shown in the following
code snippet −
<!-- A bean definition with singleton scope -->
<bean id = "..." class = "..." scope = "singleton">
<!-- collaborators and configuration for this bean go here --> </bean>
Difference Between Singleton and Prototype Bean
Singleton Prototype
A new instance is created for a single bean
Only one instance is created for a single bean
definition every time a request is made for
definition per Spring IoC container.
that bean.
Same object is shared for each request made for For each new request a new instance is
that bean. i.e. The same object is returned each created. i.e. A new object is created each
time it is injected. time it is injected.
By default, scope of a bean is singleton. So we By default, scope is not prototype, so you
don't need to declare a bean as singleton have to declare the scope of a bean as
explicitly. prototype explicitly.
Singleton scope should be used for stateless While prototype scope is used for all beans
beans. that are stateful.
Aspect-Oriented Programming (AOP) :
- In Spring Boot, AOP is a powerful feature that enhances modularity by handling cross-
cutting concerns such as logging, security, and transaction management separately from
business logic.
- Without AOP, these concerns would be scattered throughout the codebase, leading to
duplication and maintenance challenges. Spring AOP provides a lightweight proxy-based
approach to implementing AOP efficiently in enterprise applications.
Understanding AOP Concepts
• Aspect: An Aspect is a modular unit of cross-cutting concerns. For example, a logging aspect
can be applied across various methods in different classes.
• Advice: This is the action taken by an aspect at a particular join point. There are five types of
advice:
o Before: Executed before the method call.
o After: Executed after the method call, regardless of its outcome.
o AfterReturning: Executed after the method returns a result, but not if an exception
occurs.
o Around: Surrounds the method execution, allowing you to control the method
execution and its result.
o AfterThrowing: Executed if the method throws an exception.
• Join Point: A specific point in the execution of a program, such as method execution or
exception handling, where an aspect can be applied.
• Pointcut: A Pointcut is a predicate that defines where advice should be applied. It matches
join points using expressions.
• Weaving: This is the process of linking aspects with the target object. Spring AOP only
supports runtime weaving using proxy-based mechanisms (JDK dynamic proxies for
interfaces and CGLIB for concrete classes). It does not modify bytecode like AspectJ.
AOP in the Spring Framework
Spring AOP leverages proxy-based mechanisms to provide aspect-oriented functionality. It creates a
proxy object that wraps around the original object, adding the necessary advice. This proxy can be
generated automatically using configurations in XML or annotations like @Aspect
- Spring Boot is built on top of the core Spring framework.
- It simplifies and automates Spring-based application development by
reducing the need for manual configuration.
- Spring Boot follows a layered architecture, where each layer interacts
with other layers in a hierarchical order.
- The official Spring Boot documentation defines it as:
o "Spring Boot makes it easy to create stand-alone, production-
grade Spring-based applications with minimal configuration."
- "Spring Boot makes it easy to create stand-alone, production-grade
Spring-based applications with minimal configuration."
The main goal of Spring Boot is to eliminate XML and annotation-based
configuration complexities. It provides several benefits, including opinionated
defaults, convention over configuration, stand-alone applications, and
production readiness.
Spring Boot Architecture
To understand the architecture of Spring Boot, let us first see different
layers and classes present in it.
Spring Boot Layers
Spring Boot consists of the following four layers:
1. Presentation Layer: Handles HTTP requests, authentication, and
JSON conversion.
2. Business Layer: Contains business logic, validation, and
authorization.
3. Persistence Layer: Manages database interactions using ORM
frameworks like Spring Data JPA.
4. Database Layer: Stores application data using relational (MySQL,
PostgreSQL) and NoSQL databases (MongoDB, DynamoDB).
Spring Boot flow architecture
:
• Since Spring boot uses all the features/modules of spring-like
Spring data, Spring MVC etc. so the architecture is almost the
same as spring MVC, except for the fact that there is no need
of DAO and DAOImpl classes in Spring boot.
• Creating a data access layer needs just a repository class
instead which is implementing CRUD operation containing class.
• A client makes the https request(PUT/GET)
• Then it goes to controller and the controller mapped with that
route as that of request handles it, and calls the service logic if
required.
• Business logic is performed in the service layer which might be
performing the logic on the data from the database which is
mapped through JPA with model/entity class
• Finally, a JSP page is returned in the response if no error
occurred.
REST Introduction
What is REST?
The REST stands for REpresentational State Transfer.
Let's understand the meaning of each word in the REST acronym.
• State means data
• REpresentational means formats (such as XML, JSON, YAML, HTML, etc)
• Transfer means carrying data between consumer and provider using the HTTP protocol
REpresentational State Transfer
• REST was originally coined by Roy Fielding, who was also the inventor of the HTTP protocol.
• A REST API is an intermediary Application Programming Interface that enables two
applications to communicate with each other over HTTP, much like how servers
communicate to browsers.
• The REST architectural style has quickly become very popular over the world for designing
and architecting applications that can communicate.
• The need for REST APIs increased a lot with the drastic increase of mobile devices. It became
logical to build REST APIs and let the web and mobile clients consume the API instead of
developing separate applications.
2. REST Architecture
The below diagram shows the typical REST architecture:
Let's understand a few web service term's by looking into the above architecture:
- Request and Response: Request is the input to a web service, and the response is the output
from a web service.
- Message Exchange Format: It is the format of the request and response. There are two
popular message exchange formats: XML and JSON.
- Service Provider or Server: The service provider is one that hosts the web service.
- Service Consumer or Client: A service consumer is one who is using a web service.
It is the responsibility of the consumer means client application to prepare and send HTTP request
message
It is the responsibility of the business component (developed by a service provider) to prepare and
send the HTTP response message
3. REST Architectural Constraints
An API that has the following constraints is known as RESTful API:
- Client-server architecture: The client is the front-end and the server is the back-end of the
service. It is important to note that both of these entities are independent of each other.
- Stateless: No data should be stored on the server during the processing of the request
transfer. The state of the session should be saved at the client’s end.
- Cacheable: The client should have the ability to store responses in a cache. This greatly
improves the performance of the API.
- Uniform Interface: This constraint indicates a generic interface to manage all the interactions
between the client and server in a unified way, which simplifies and decouples the
architecture.
- Layered System: The server can have multiple layers for implementation. This layered
architecture helps to improve scalability by enabling load balancing.
- Code on Demand: This constraint is optional. This constraint indicates that the functionality
of the client applications can be extended at runtime by allowing a code download from the
server.
REST Key Concepts
Resource
The fundamental concept of a REST-based system is the resource. A resource is anything you want to
expose to the outside world, through your application.
Example 1: Resources for Employee Management System:
- Employee
- Department
- Projects
- Task
- Address
Example 2: Resources for Student Management System:
- Student
- Teacher
- School
- Class
- Subject
URI - Uniform Resource Identifier
The resource can be identified by a Uniform Resource Identifier (URI). For web-based systems, HTTP
is the most commonly used protocol for communicating with external systems. You can identify a
unique resource using a URI.
Consider, we are developing a simple blog application and you can define URIs for a blog Post
resource:
GET—[Link] Returns a list of all posts
GET—[Link] Returns a post whose ID is 2
POST—[Link] Creates a new Post resource
PUT—[Link] Updates a POST resource whose ID is 2
DELETE—[Link] Deletes a POST resource whose ID is 2
Sub-resource
In REST, the relationships are often modeled by a sub-resource. Use the following pattern for sub-
resources.
GET /{resource}/{resource-id}/{sub-resource}
GET /{resource}/{resource-id}/{sub-resource}/{sub-resource-id}
POST /{resource}/{resource-id}/{sub-resource}
Example:
GET /{post}/{post-id}/{comments}
GET /{post}/{post-id}/{comments}/{comment-id}
POST /{post}/{post-id}/{comments}
Use sub-resources child object cannot exist without its parent.
HTTP Methods
Common HTTP verbs:
• GET—To get a collection or a single resource
• POST—To create a new resource
• PUT—To update an existing resource
• DELETE—To delete a collection or a single resource
HTTP Status Code
Some of the frequently used status codes in this class are as follows:
• 200 OK: This code indicates that the request is successful and the response content is
returned to the client as appropriate.
• 201 Created: This code indicates that the request is successful and a new resource is created.
• 400 Bad Request: This code indicates that the server failed to process the request because of
the malformed syntax in the request. The client can try again after correcting the request.
• 401 Unauthorized: This code indicates that authentication is required for the resource. The
client can try again with appropriate authentication.
• 403 Forbidden: This code indicates that the server is refusing to respond to the request even
if the request is valid. The reason will be listed in the body content if the request is not a
HEAD method.
• 404 Not Found: This code indicates that the requested resource is not found at the location
specified in the request.
• 500 Internal Server Error: This code indicates a generic error message, and it tells that an
unexpected error occurred on the server and that the request cannot be fulfilled.