Define String framework with its advantages.
Spring Framework:
• Open-Source and a lightweight framework.
• Standalone and Enterprise application can be developed
• Released in 2003(initial), 2004(production)
• Developed by Rod Johnson
• It can be thought of as a framework of frameworks because it
provides support to various frameworks such as Struts, Hibernate,
Tapestry, EJB, JSF, etc
• The framework, in broader sense, can be defined as a structure
where we find solution of the various technical problems.
• The Spring framework comprises several modules such as IOC, AOP,
DAO, Context, ORM, WEB MVC etc.
Advantages of Spring Framework
They are as follows:
1) Predefined Templates: Spring framework provides templates for JDBC,
Hibernate, JPA etc. technologies. So there is no need to write too much code.
It hides the basic steps of these technologies.Let's take the example of
JdbcTemplate, you don't need to write the code for exception handling,
creating connection, creating statement, committing transaction, closing
connection etc. You need to write the code of executing query only. Thus, it
save a lot of JDBC code.
2) Loose Coupling: The Spring applications are loosely coupled because of
dependency injection.
3) Easy to test: The Dependency Injection makes easier to test the application.
The EJB or Struts application require server to run the application but Spring
framework doesn't require server.
4) Lightweight: Spring framework is lightweight because of its
POJO implementation. The Spring Framework doesn't force the
programmer to inherit any class or implement any interface. That is
why it is said non-invasive.
5) Fast Development: The Dependency Injection feature of Spring
Framework and it support to various frameworks makes the easy
development of JavaEE application.
6) Powerful abstraction: It provides powerful abstraction to JavaEE
specifications such as JMS(Java Message Service), JDBC, JPA(Java
Persistence API) and JTA(Java Transaction API).
7) Declarative support: It provides declarative support for caching,
validation, transactions and formatting.
Spring FW Architecture
It consists of features organized into
about 20 modules.
These modules are grouped into
Core Container,
Data Access/Integration,
Web, AOP (Aspect Oriented
Programming),
Instrumentation, and Test, as shown
in the following diagram.
Spring Core Basics:
Spring Core is the foundation of the Spring Framework.
It provides the basic functionality that powers all other modules —
especially object creation, dependency injection, and bean lifecycle
management.
In simple words: Spring Core = Core engine that manages our Java
objects (called beans) using IoC and DI.
Basics of Spring Core:
5 most important basic concepts of Spring Core:
1. IoC (Inversion of Control): Usually, classes create their own dependencies using new. But in
Spring, the control is inverted — Spring creates the objects and injects them where needed.
This reduces tight coupling between classes.
2. Dependency Injection (DI): When one class needs another class, Spring injects that
required object automatically. DI can be done in three ways: Constructor Injection, Setter
Injection, Field Injection (using @Autowired)
3. Beans: A Bean is simply a Java object managed by the Spring container. It can be declared
using: XML configuration: <bean> tags, Java configuration: @Bean in @Configuration class,
Annotations: @Component, @Service, @Repository, etc.
4. IoC Container: The IoC Container is the core part of Spring that creates, manages, and wires
beans. Two main types: i) BeanFactory: Basic container (not commonly used now)
ii) ApplicationContext: Advanced container with extra features (widely used)
5. Bean Lifecycle: Spring manages the entire life of a bean: Bean is created, Dependencies are
injected, Bean is initialized, Bean is used, Bean is destroyed
Overall, Spring Core gives the basic foundation (IoC + DI + Beans + Container) that makes
Spring a powerful and flexible framework.
Describe the Dependency Injection and its types
DI is a design pattern(reusable solution to a common problem in software design.) that
removes the dependency from the programming code so that it can be easy to manage and
test the application. Object gets its dependencies from outside, rather than creating them
itself. The framework takes responsibility for providing the required dependencies (objects) to
other objects (beans).
Why Use Dependency Injection
Loose Coupling: Classes don't depend tightly on each other. Easy to maintain and test.
Easy Testing: We can inject mock objects easily during unit testing.
Reusability: We can reuse and manage dependencies centrally.
Imagine a Car depends on an Engine. Instead of Car creating the Engine itself (new
Engine()), someone else (Spring) gives the Engine to the Car.
Dependency • Example of dependency
• Code has very high degree of coupling due to aggregation
• To create Object of class Person, we depend on Address
Object, and to create Address object, we need contact
There three types of dependency Injections
Type Description Used With
Dependencies are passed via
Constructor Injection Recommended
constructor
Dependencies are set via public
Setter Injection Optional
setters
Dependencies are injected directly Quick but not recommended
Field Injection
into field for testing
Inversion of Control(IoC) and its types
• IoC is a design principle that emphasizes keeping Java classes
independent of each other.
• IoC is achieved through Dependency Injection (DI).
• IoC refers to transferring the control of objects and their
dependencies from the main program to a container or
framework.
• The IoC container uses two primary mechanisms to work:
Bean instantiation:
• The IoC container is responsible for creating and configuring
beans. This can be done through XML configuration, Java
annotations, or a combination of both.
Dependency injection:
• The IoC container injects dependencies into beans. This means
that the IoC container is responsible for providing beans with the
Spring Container
• The Spring container is the core of the Spring Framework.
• Manages Bean Objects(create, initialize, destroy)[Life cycle of bean]
• It is responsible for creating, configuring, and managing the objects
that make up your application.
• The container uses a technique called dependency injection to
manage the relationships between objects.
• Transaction Management
Spring container are of TWO TYPES
1. Bean factory(old Method)
2. ApplicationContext(new Method)
1.BeanFactory: It is the simplest container provided by Spring to
manage beans. It lazily loads beans — i.e., creates bean objects
only when you request them.
2. ApplicationContext:It’s a more powerful version of
BeanFactory. It eagerly loads all beans on startup. Supports
additional features like:
Internationalization (i18n), Event propagation,
Annotation-based configuration, AOP
integration, Bean lifecycle callbacks
Difference between constructor injection and setter injection
Spring IoC (Inversion of Control) Spring Dependency Injection
Spring IoC Container is the core of Spring
Spring DI is a way to inject the dependency of a
Framework. It creates the objects, configures and
framework component by the following ways of
assembles their dependencies, manages their entire
spring: Constructor Injection and Setter Injection
life cycle.
Spring helps in creating objects, managing objects, Spring framework helps in the creation of loosely-
configurations, etc. because of IoC coupled applications because of DI
DI is the method of providing the dependencies
Spring IoC is achieved through DI.
and IoC is the end result of DI
IoC is a design principle where the control flow of
DI is one of the subtypes of the IOC principle.
the program is inverted.
AOP Dependency look up are other ways to In case of any changes in business requirements,
implement Inversion of Control. no code change is required.
Aspect-Oriented Programming (AOP)
• It helps in separating common code (like logging, security, transactions)
from our main business logic i.e. it allows developers to modularize
cross-cutting concerns.
• Thus, makes the code more modular, reusable, and maintainable.
• Spring AOP is a popular implementation of AOP. It provides a simple and
powerful way to write custom aspects.
• Two ways to use AOP in Spring:
- Schema-based approach (XML config)
- @AspectJ annotation style (Java annotations).
Benefits of Spring AOP:
Used for things like declarative transaction management.
Helps in writing custom aspects that work with our object-oriented code.
Benefits of using AOP
Modularity:
• AOP allows developers to separate cross-cutting concerns from the main
program logic. This makes the code more modular, reusable, and
maintainable.
Reusability:
• Aspects can be reused across multiple projects. This saves time and effort,
and it can help to improve the consistency of code.
Maintainability:
• AOP makes it easier to maintain code. This is because cross-cutting concerns
are separated from the main program logic. This makes it easier to
understand and modify the code.
BEAN SCOPE
• In Spring F/W, a bean's scope determines how long it lives and how many instances of it are
created.
• The default scope is singleton, which means that only one instance of the bean is created and shared
across the entire application context.
• The prototype scope creates a new instance of the bean each time it is requested. This is useful for
beans that are not thread-safe or that need to be customized for each request.
• The request scope creates a new instance of the bean for each HTTP request. This is useful for beans
that need to be associated with a specific request, such as a database connection or a shopping cart.
• The session scope creates a new instance of the bean for each user session. This is useful for beans
that need to be associated with a specific user, such as a user profile or a shopping cart.
• The global session scope creates a new instance of the bean for each user session across all
applications in the same cluster. This is useful for beans that need to be shared across multiple
applications, such as a user profile or a shopping cart.
• The application scope A single bean instance is created per application (ServletContext).This means
the bean will be shared across the entire web application, for all HTTP requests and all sessions. It’s
available as long as the web application is running.
• We can specify the scope of a bean using the @Scope annotation. For
example, the following code creates a bean with the prototype scope:
@Scope("prototype")
public class MyBean {
// ...
} OR
<bean class="com.test.DIDemo.Employee" name="stud1"
scope="request">
<property…
</bean>
WebSocket API
• It is a way for the client (browser) and server to keep a live, real-time
two-way connection open.
Examples: In chat apps, messages appear instantly, Stock prices update in
real-time without refreshing the page.
• Spring Framework provides a WebSocket API that works with many
servers like: Tomcat, Jetty, GlassFish, WebLogic, Undertow, etc.
• We don’t have to worry about server details—Spring handles it. We just
write our WebSocket logic.
• This API allows developers to easily implement
WebSocket-based applications.
• The Spring Framework also provides a number of features
that make it easy to develop WebSocket-based
applications, including:
1. STOMP(Simple Text Oriented Messaging Protocol)Messaging
Support:
- It’s used to send and receive messages on top of WebSocket.
- It works over any reliable two-way protocol like TCP or
WebSocket.
2. Spring provides a ready-to-use JavaScript library.
3. Spring gives some sample apps like: A Chat Application, A Stock
Ticker (for live stock updates)
Thus, Spring WebSocket makes it easy to build real-time apps with
simple code, server compatibility, and built-in tools.
Autowiring
Autowiring in the Spring framework can inject
dependencies automatically.
• The Spring container detects those dependencies specified
in the configuration file and the relationship between the
beans. This is referred to as Autowiring in Spring.
• Autowiring in Spring internally uses constructor injection.
• An autowired application requires fewer lines of code
comparatively but at the same time, it provides very little
flexibility to the programmer.
Modes Description
This mode tells the framework that autowiring is not supposed to be
No done. It is the default mode used by Spring.
byName It uses the name of the bean for injecting dependencies.
byType It injects the dependency according to the type of bean.
Constructor It injects the required dependencies by invoking the constructor.
Autodetect(dep
recated in The autodetect mode uses two other modes for autowiring –
Spring 3) constructor and byType.
1. No
This mode tells the framework that autowiring is not supposed to be done. It is the
default mode used by Spring.
2. byName
It uses the name of the bean for injecting dependencies. However, it requires that the name
of the property and bean must be the same. It invokes the setter method internally for
autowiring.
<bean id="state" class=“pack.State">
<property name="name" value="UP" />
</bean>
<bean id="city" class=“pack.City" autowire="byName"></bean>
3. byType
It injects the dependency according to the type of the bean. It looks up in
the configuration file for the class type of the property. If it finds a bean
that matches, it injects the property. If not, the program throws an error.
The names of the property and bean can be different in this case. It
invokes the setter method internally for autowiring.
<bean id="state" class="sample.State">
<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="byType"></bean>
4. constructor: It injects the required dependencies by invoking the constructor. It works
similar to the “byType” mode but it looks for the class type of the constructor arguments. If
none or more than one bean are detected, then it throws an error, otherwise, it autowires the
“byType” on all constructor arguments.
<bean id="state" class="sample.State">
<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="constructor"></bean>
5. autodetect: The autodetect mode uses two other modes for autowiring – constructor and
byType. It first tries to autowire via the constructor mode and if it fails, it uses the byType
mode for autowiring. It works in Spring 2.0 and 2.5 but is deprecated from Spring 3.0 onwards.
<bean id="state" class="sample.State">
<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="autodetect"></bean>
class City { package com.test.DemoProject;
private int id; Auto wiring example import
private String name; org.springframework.beans.factory.annotation.Autowired;
private State s; dependency public class State {
public City() {
private String name;
}
public String getName() { return name; }
public int getID() { return id; }
public void setId(int eid) { this.id = eid; } public void setName(String s) { this.name = s; }
public String getName() { return name; } @Override
public void setName(String st) { this.name = st; } public String toString() {
public State getS() { return "State [name=" + name + "]";
return s; }
} public State(String name) {
public void setS(State s) { super();
this.s = s; this.name = name;
} }
public int getId() {
public State() {
return id;
super();}
}
public City(State s) { }
super(); package com.test.DemoProject; //main
this.s = s; import org.springframework.context.ApplicationContext;
} import
public City(int id, String name, State s) {
org.springframework.context.support.ClassPathXmlApplicationContex
super();
this.id = id; t;
this.name = name; public class Test {
this.s = s; public static void main(String[] args) {
} ApplicationContext context = new
@Override ClassPathXmlApplicationContext("/com/test/DemoProject/config1.xml
public String toString() { ");
return "City [id=" + id + ", name=" + name + ", s=" + s + City city=context.getBean("city", City.class);
"]"; System.out.println(city);
} }
} }
<xml version="1.0" encoding="UTF-8"> <xml version="1.0" encoding="UTF-8">
<beans <beans
xmlns="http://www.springframework.org/schema/ xmlns="http://www.springframework.org/schema/bea
beans" ns"
xmlns:xsi="http://www.w3.org/2001/XMLSchema- xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance" instance"
xmlns:p="http://www.springframework.org/ xmlns:p="http://www.springframework.org/schema/
schema/p" p"
xmlns:context="http:// xmlns:context="http://www.springframework.org/
www.springframework.org/schema/context" schema/context"
xsi:schemaLocation="http:// xsi:schemaLocation="http://
www.springframework.org/schema/beans www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/ http://www.springframework.org/schema/beans/
spring-beans.xsd spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context
http://www.springframework.org/schema/ http://www.springframework.org/schema/context/
context/spring-context.xsd"> spring-context.xsd">
<bean id="s" <bean id="s" class="com.test.DemoProject.State"
class="com.test.DemoProject.State" > >
<property name="name" value="UP" /> <property name="name" value="UP" />
</bean> </bean>
<bean name="city" <bean name="city"
class="com.test.DemoProject.City" class="com.test.DemoProject.City"
autowire="constructor"> autowire="byName">
<property name="id" value="11" /> <property name="id" value="11" />
<property name="name" value="Washington, <property name="name" value="Washington,
D.C." /> D.C." />
@autowired
There are three ways to apply the @Autowired annotation:
NOTE: PUT FOLLOWING LINE IN CONFIG.XML FILE
<context:annotation-config/>
1. On a field: This is the most common way to use the @Autowired annotation. Simply annotate the field with @Autowired and
Spring will inject an instance of the dependency into the field when the bean is created.
public class MyBean {
@Autowired
private MyDependency dependency; }
2. On a constructor: You can also use the @Autowired annotation on a constructor. This will
cause Spring to inject an instance of the dependency into the constructor when the bean is
created.
public class MyBean {
private MyDependency dependency;
@Autowired
public MyBean(MyDependency dependency) {
this.dependency = dependency;
} }
3. On a setter method: You can also use the @Autowired annotation on a setter
method. This will cause Spring to inject an instance of the dependency into the
setter method when the bean is created.
public class MyBean {
private MyDependency dependency;
@Autowired
public void setDependency(MyDependency dependency)
{
this.dependency = dependency;
}
}
The @Autowired annotation can be used on any field, constructor, or setter
method that is declared in a Spring bean. The dependency that is injected
must be a Spring bean itself.
Life Cycle Call backs
• Bean life cycle is managed by the spring container. When we run the program then,
first of all, the spring container gets started. After that, the container creates the
instance of a bean as per the request, and then dependencies are injected. And finally,
the bean is destroyed when the spring container is closed. Therefore, if we want to
execute some code on the bean instantiation and just after closing the spring container,
then we can write that code inside the custom init() method and the destroy() method.
package com.kiet.FirstProject;
public class Employee { <bean name="employee"
private int eid;
private String name;
class="com.kiet.FirstProject.Employee" init-
public Employee() { method="init" destroy-method="destroy">
super();
}
<property name="eid" value="21"/>
public Employee(int eid, String name) { <property name="name" value="Rohit Sharma"/>
super();
this.eid = eid;
</bean>
this.name = name;
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getName() {
AbstractApplicationContext context=new
return name; ClassPathXmlApplicationContext("/com/kiet/FirstProject/conf.xm
} l");
public void setName(String name) {
this.name = name;
Employee emp=context.getBean("employee",Employee.class);
} context.registerShutdownHook();
public void init() System.out.println(emp);
{
System.out.println("initialized");
}
public void destroy()
{
System.out.println("destroyed");
}
@Override
public String toString() {
return "Employee [eid=" + eid + ", name=" + name +
"]";
}}
Bean Configuration styles in spring framework
1. XML-based configuration: Traditional approach where beans are defined in XML
configuration files (applicationContext.xml).
<bean name="address1" class="com.kiet.TEST.Address">
<property name="city" value="Ghaziabad"/>
<property name="state" value="UP"/>
</bean>
2. Annotation-based configuration:Uses annotations like @Component, @Service,
@Repository, and @Autowired for dependency injection and bean declaration.
Add following tag to config file.
<context:annotation-config/>
<context:component-scan base-package="com.kiet.TEST"/>
@Component
public class Employee {
@Value("12")
ApplicationContext context=New
private int id; ClassPathXmlApplicationContext("/com/kiet/TEST/configStereo.
@Value("Raja") xml");
private String name; Employee emp=context.getBean("employee", Employee.class);
public Employee() { System.out.println(emp);
}
public Employee(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + "]";
}}
3. Java-based Configuration (JavaConfig):Configuration is done using Java classes annotated with
@Configuration.Beans are defined using @Bean annotations within these configuration classes.
@Component
public class Employee {//Employee.java
void doSomething()
{
System.out.println("employee object created");
}
}
//APP JAVA
ApplicationContext context=new
AnnotationConfigApplicationContext(EmpConfig.class);
Employee emp=context.getBean("employee", Employee.class);
emp.doSomething();
@Configuration // EmpConfig.java
@ComponentScan(basePackages = "com.kiet.TESTa")
public class EmpConfig {
@Bean
public Employee getEmployee() {
return new Employee();
}
}
SPRING BOOT
SPRING BOOT
Spring Boot is an open-source Java framework that makes it easy to create Spring-based applications. It
provides a number of features that make development faster and easier, including:
Auto-configuration:
• Spring Boot can automatically configure many of the beans that we need for our application, based on
the dependencies that we have included. This means that we don't have to spend time writing a lot of
XML configuration files.
Embedded servers:
• Spring Boot can embed a number of different web servers, such as Tomcat and Jetty. This means that we
don't have to deploy our application to a separate server.
Starter projects:
• Spring Boot provides a number of starter projects that wecan use to get started quickly with different
types of applications, such as web applications, RESTful web services, and batch applications.
Microservices:
• Spring Boot is a popular choice for developing microservices, which are small, independent services
that can be combined to create a larger application. Spring Boot makes it easy to develop and deploy
microservices, and it provides a number of features that are useful for microservices, such as embedded
servers and service discovery.
Springboot Key Features
• Built on top of Spring Framework
• Simplifies development and deployment of Spring applications
• Auto-configuration
• Starter dependencies
• Opinionated defaults
• Embedded servers (Tomcat, Jetty, etc.)
• Production-ready features (metrics, health checks, etc.)
Benefits of Spring Boot
• Faster development time
• Reduced boilerplate code
• Integrated development environment
• Easy deployment (self-contained JARs)
• Microservices architecture support
SPRING BOOT BUILD SYSTEMS
Spring Boot supports several build systems, but it primarily
recommends two: Maven and Gradle
These build systems are recommended because they offer excellent
support for dependency management.
• Maven: Maven uses an XML file (pom.xml) for its configuration. It
provides a uniform build system and a quality project information.
Spring Boot’s spring-boot-starter-parent project can be used as a
parent project in Maven to provide sensible defaults.
• Gradle: Gradle uses Groovy-based DSL (Domain Specific Language)
for its configuration. It’s known for its performance and flexibility.
Maven Gradle
Based On based on developing pure Java language-based based on developing domain-specific
software language projects
Configuration Maven uses an XML file for its configuration and Gradle uses a Groovy-based Domain-Specific
follows strict conventions. This makes it easy for Language (DSL) for its configuration,
developers to understand the layout of a providing more flexibility in the build process
project, but also limits customization options
Performance Maven, in terms of execution of projects, is Gradle is known for its performance and is
quite slow generally faster than Maven2. It uses
mechanisms like incrementality, build cache,
and the Gradle Daemon for work avoidance
and faster builds
Flexibility Maven provides a very rigid model that makes Gradle is highly customizable and can be
customization tedious and sometimes modified under various technologies for
impossible. diverse projects
User Maven’s longer tenure means that its support Gradle’s IDE support continues to improve
Experience through IDEs is better for many users quickly
Dependency Both Gradle and Maven offer excellent support for dependency management. However,
Management Gradle’s mechanisms for work avoidance and incrementality make it much faster than Maven
Structuring Spring Boot Code
Spring Boot does not require any specific code layout to work. However, there
are some best practices that help.
According to Spring boot documentation:
Place the main application class in a root package above other classes. The
@EnableAutoConfiguration annotation is often placed on main class, and it
implicitly defines a base “search package” for certain items. For example, if you
are writing a JPA application, the package of the @EnableAutoConfiguration
annotated class is used to search for @Entity items.
Using a root package also lets the @ComponentScan annotation be used
without needing to specify a basePackage attribute. You can also use the
@SpringBootApplication annotation if your main class is in the root package.
Main class
package com.example.myapplication;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Spring Boot Runners
Spring Boot Runners are interfaces that allow you to execute code when a Spring
Boot application starts. They are typically used to perform some initialization or
setup tasks before the application starts processing requests.
There are two types of runners:
CommandLineRunner:
• This is the legacy runner that was introduced in Spring Boot 1.0. It has one
abstract method, run(String... args): void.
ApplicationRunner:
• This is a newer runner that was introduced in Spring Boot 1.3. It has one abstract
method, run(ApplicationArguments args) throws Exception.
The main difference between the two runners is that the ApplicationRunner gives
you access to the application arguments, while the CommandLineRunner does not.
Logger
A logger in Spring Boot is a tool that helps developers track and monitor
the events that happen in their application. It is a crucial part of any
application, as it can help identify and fix errors, as well as track
performance and usage.
Spring Boot comes with a built-in logger, which is based on the popular
Logback logging framework. This logger can be used to log messages to
the console, to a file, or to a remote server.
Benefits of using a logger in Spring Boot:
• Improved debugging
• Better performance monitoring
• Increased security
• Enhanced compliance
BASICS OF WEB APPLICATIONS
• Localhost: In a computer network, localhost refers to the
computer you are using to send a loopback request. This
request is data from your computer acting as a virtual
server, which is sent back to itself without ever passing
through a physical network.
• Server at localhost refers to your own machine is
hosting(server) at “localhost” or http://127.0.0.1
• Spring Boot has inbuilt “tomcat-apache” server.(no
external installation is required.
<!DOCTYPE html>
<html> result
<head>
<meta charset="ISO-8859-1">
<title>Index</title>
</head>
<body>
<form action="#app" method="get"><br>
<input type="text" placeholder="Name"/><br>
<input type="password"
placeholder="Password">
<input type="submit" value="submit">
</form>
</body>
</html>
Method can be get, post, put, delete, options etc
GET, POST, PUT, and DELETE are HTTP methods that define how clients and servers communicate over the World
Wide Web. HTTP methods enable API clients to perform CRUD (Create, Read, Update, and Delete) actions on an
API’s resources in a standardized and predictable way. The most commonly used HTTP methods are:
GET
The GET method is used to retrieve data on a server. Clients can use the GET method to access all of the resources of
a given type, or they can use it to access a specific resource. For instance, a GET request to the /products endpoint of
an e-commerce API would return all of the products in the database, while a GET request to the /products/123
endpoint would return the specific product with an ID of 123. GET requests typically do not include a request body, as
the client is not attempting to create or update data.
POST
The POST method is used to create new resources. For instance, if the manager of an e-commerce store wanted to add
a new product to the database, they would send a POST request to the /products endpoint. Unlike GET requests, POST
requests typically include a request body, which is where the client specifies the attributes of the resource to be
created. For example, a POST request to the /products endpoint might have a request body that looks like this:
{
"name": "Sneakers",
"color": "blue",
"price": 59.95,
"currency": "USD"
}
PUT
The PUT method is used to replace an existing resource with an updated version. This method works by
replacing the entire resource (i.e., the specific product located at the /products/123 endpoint) with the
data that is included in the request’s body. This means that any fields or properties not included in the
request body are deleted, and any new fields or properties are added.
PATCH
The PATCH method is used to update an existing resource. It is similar to PUT, except that PATCH
enables clients to update specific properties on a resource—without overwriting the others. For instance,
if you have a product resource with fields for name, brand, and price, but you only want to update the
price, you could use the PATCH method to send a request that only includes the new value for the price
field. The rest of the resource would remain unchanged. This behavior makes the PATCH method more
flexible and efficient than PUT.
DELETE
The DELETE method is used to remove data from a database. When a client sends a DELETE request, it
is requesting that the resource at the specified URL be removed. For example, a DELETE request to
the /products/123 endpoint will permanently remove the product with an ID of 123 from the database.
Some APIs may leverage authorization mechanisms to ensure that only clients with the appropriate
permissions are able to delete resources.
Describe the flow of HTTPS requests through the Spring Boot application.The
flow of HTTPS requests through a Spring Boot application is as follows:
1. First client makes an HTTP request (GET, POST, PUT, DELETE) to
the browser.
2. After that the request will go to the controller, where all the
requests will be mapped and handled.
3. After this in Service layer, all the business logic will be
performed. It performs the business logic on the data that
is mapped to JPA (Java Persistence API) using model classes.
4. In repository layer, all the CRUD operations are being done for
the REST APIs.
5. A JSP page is returned to the end users if no errors are there
Creating “hello world” application in Spring Boot
Step 1: https://start.spring.io/
Step 2:
Dependencies add Web
Language Java
Build Maven
Group id com.myorganization
Artifact SpringBootDemo
Step 3:
Press Generate
Step 4:
Unzip downloaded project
Step 5: Step 6:
click click
import next
Step 7:
click
Select
folder
Step 8:check application Step 10: Create end points in controller
package com.kiet.FirstSBProject;
import org.springframework.stereotype.Controller;
import
org.springframework.web.bind.annotation.GetMapping;
import
org.springframework.web.bind.annotation.RequestParam;
import
org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@GetMapping("/hello")//END POINT -1
Step 9: Add controller @ResponseBody
public String hello(@RequestParam(value = "name",
defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
@GetMapping("/hi")//END POINT -2
@ResponseBody
public String hello() {
return "hi";
}
}
Step 11: run main
Step 12: see logs
Step 13: test 1
Step 14: test 2
Spring Boot Starters
Spring Boot Starters are a set of convenient dependency descriptors that
you can include in your application. They help you get a project up and
running quickly by providing a collection of curated dependencies that
are commonly used together.
Commonly Used Starters
spring-boot-starter-web
•Purpose: For building web applications using Spring MVC.
•Includes: Spring MVC, embedded Tomcat/Jetty/Undertow server, and necessary
dependencies for web development.
spring-boot-starter-data-jpa
Purpose: For using Spring Data JPA with Hibernate for data persistence.
Includes: Spring Data JPA, Hibernate, JDBC, and necessary dependencies for database
access and ORM.
spring-boot-starter-security
Purpose: For adding security to Spring Boot applications.
Includes: Spring Security, OAuth, and other security-related dependencies.
RESTFUL WEB SERVICES
RESTful web services are a type of web service
that uses the HTTP protocol to communicate with
clients. They are based on the Representational
State Transfer (REST) architectural style, which
defines a set of constraints that make web
services more interoperable and scalable.
REST Controller
• A REST controller is a type of controller that is used to create RESTful web
services. REST stands for REpresentational State Transfer, and it is an architectural
style for designing web services.
• REST controllers are typically annotated with the @RestController annotation. This
annotation tells Spring that the controller is a REST controller, and it enables a
number of features that are useful for developing RESTful web services, such as
automatic serialization of responses to JSON or XML.
@RestController
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello, world!";
}
}
Request Mapping: @RestController
•Request Mapping is an annotation that is @RequestMapping("/student")
public class StudentController {
used to map web requests to specific handler
StudentService studentService;
classes and/or handler methods. public
•The annotation is used at the class level to StudentController(StudentService
express shared mappings or at the method studentService) {
level to narrow down to a specific endpoint super();
mapping. this.studentService = studentService;
•The annotation has various attributes to }
match by URL, HTTP method, request @PostMapping
parameters, headers, and media types. Student addStudent(@RequestBody
Student student)
{
Request Body: return
•A request body is data sent by the client to this.studentService.addStudent(studen
your API. t);
•It is typically used when we expect the client }
to send data in the request body when }
submitting a form or sending JSON data.
•You can use the @RequestBody annotation
in Spring Boot to bind the HTTP request body
Path Variable:
@GetMapping("/{id}")
•Path variables are used to extract values
Student getStudent(@PathVariable int
from the URI and use them as method id)
parameters. {
•You can use the @PathVariable annotation in return
Spring Boot to extract values from the URI this.studentService.getStudent(id);
path. }
•Path variables are typically used to handle
dynamic URIs where one or more of the URI
value works as a parameter.
@ResponseBody
Request Parameter: public String hello(@RequestParam(value =
•Request parameters are used to extract "name", defaultValue = "World") String
input data passed through an HTTP URL or name) {
return String.format("Hello %s!", name);
passed as a query. }
•You can use the @RequestParam annotation
in Spring Boot to extract input data passed
through an HTTP URL or passed as a query.
•Request parameters are typically used to
filter data or to pass additional information to
GET, POST, PUT, and DELETE
GET, POST, PUT, and DELETE are the four most common
HTTP methods used in Spring Boot.
• GET: is used to retrieve data from a server.
• POST: is used to create new data on a server.
• PUT: is used to update existing data on a server.
• DELETE: is used to delete data from a server.
• In Spring Boot, these methods are mapped to controller
methods using the @GetMapping, @PostMapping,
@PutMapping, and @DeleteMapping annotations,
respectively.
Why Spring Boot is preferred over any other framework Describe the key
dependencies of Spring Boot.
The Spring cloud that comes with Spring Boot, includes vast libraries, which
is one of the major reasons why most developers prefer the Java-based
Spring Boot. In addition, Spring Boot offers superior compatibility with
Spring frameworks, and it also provides excellent support for docker
containerization, heightening performance, and usability. Some of the most
compelling reasons for using Spring Boot include:
• Provides the best means to configure Java beans
• Offers robust batch processing
• Helps users effectively manage Representational State Transfer (REST)
endpoints
• Integrates an auto-configuration tool, eliminating the need for manual
configuration
• Enables annotation-based configurations
• Ease of dependency management
Key dependencies of Spring Boot
Mentioned below are important Spring Boot dependencies that
need to be added to a Gradle-based or Maven-based application, to
ensure application compatibility with Spring Boot features.
• spring-boot-starter-parent
• spring-boot-maven-plugin
• spring-boot-starter-test
• spring-boot-starter-security
• spring-boot-starter-actuator
• Spring-boot-starter-web
Explain the basic Spring Boot Annotations
@SpringBootApplication: This is the main annotation used to
bootstrap a Spring Boot application. It combines three
annotations: @Configuration, @EnableAutoConfiguration,and
@ComponentScan. It is typically placed on the main class of the
application.
@Configuration: This annotation is used to indicate that a
class contains configuration methods for the application
context. It is typically used in combination with
@Beanannotations to define beans and their dependencies.
@Component: This annotation is the most generic annotation
for any Spring-managedcomponent. It is used to mark a class as a
Spring bean that will be managed by the Springcontainer.
@RestController: This annotation is used to define a RESTful web
service controller. It is a specialized version of the @Controller
annotation that includes the @ResponseBody annotation by
default.
@RequestMapping: This annotation is used to map HTTP requests to
a specific method in acontroller. It can be applied at the class level to
define a base URL for all methods in the class,or at the method level
to specify a specific URL mapping.
Feature Spring Framework Spring Boot
Automatic (annotations +
Configuration Manual (XML/Java)
auto config)
Needs external server (e.g. Comes with embedded
Server Setup
Tomcat) server
Simplified & fast
Complexity More complex setup
development
Learning Curve Steeper Easier for beginners
Core foundation of all Spring Rapid development &
Main Aim
modules microservices ready