Understanding Spring Framework in Java
Understanding Spring Framework in Java
Unit-V(Spring Framework)
Introduction:-Prior to the advent of Enterprise Java Beans (EJB), Java developers needed to
use JavaBeans to create Web applications. Although JavaBeans helped in the development of user
interface (UI) components, they were not able to provide services, such as transaction management
and security, which were required for developing robust and secure enterprise applications. The
advent of EJB was seen as a solution to this problem EJB extends the Java components, such as Web
and enterprise components, and provides services that help in enterprise application development.
However, developing an enterprise application with EJB was not easy, as the developer needed to
perform various tasks, such as creating Home and Remote interfaces and implementing lifecycle
callback methods which lead to the complexity of providing code for EJBs Due to this complication,
developers started looking for an easier way to develop enterprise applications.
The Spring framework(which is commonly known as Spring) has emerged as a solution to all these
complications This framework uses various new techniques such as Aspect-Oriented Programming
(AOP), Plain Old Java Object (POJO), and dependency injection (DI), to develop enterprise applications,
thereby removing the complexities involved while developing enterprise applications using EJB, Spring
is an open source lightweight framework that allows Java EE 7 developers to build simple, reliable,
and scalable enterprise applications. This framework mainly focuses on providing various ways to help
you manage your business objects. It made the development of Web applications much easier as
compared to classic Java frameworks and Application Programming Interfaces (APIs), such as Java
database connectivity(JDBC), JavaServer Pages(JSP), and Java Servlet.
The Spring framework consists of seven modules which are shown in the above Figure. These modules
are Spring Core, Spring AOP, Spring Web MVC, Spring DAO, Spring ORM, Spring context, and Spring
Web flow. These modules provide different platforms to develop different enterprise applications; for
example, you can use Spring Web MVC module for developing MVC-based applications.
1. Explicit Configuration: XML configuration provides explicit and detailed control over the
configuration of Spring components. Developers can specify beans, dependencies, and other
settings in a structured and well-defined format.
2. Flexibility: XML allows for more complex and dynamic configurations since it is not tied to the Java
language. XML configuration can be externalized from the code, which is useful in scenarios where
configurations need to be modified without touching the application’s source code.
Which One to Use?
In modern Spring applications, annotations are often favored due to their simplicity, readability, and
compile-time checking. They promote a more “code-centric” approach to configuration, making it
easier to manage and understand.
However, XML configuration can still be useful, especially in cases where complex or dynamic
configurations are required, or when externalizing configurations is a priority.
Bean Scopes
When you create a bean definition, you create a recipe for creating actual instances of the class defined by that
bean definition. The idea that a bean definition is a recipe is important, because it means that, as with a class, you
can create many object instances from a single recipe.
You can control not only the various dependencies and configuration values that are to be plugged into an object
that is created from a particular bean definition but also control the scope of the objects created from a particular
bean definition. This approach is powerful and flexible, because you can choose the scope of the objects you create
through configuration instead of having to bake in the scope of an object at the Java class level. Beans can be
defined to be deployed in one of a number of scopes. The Spring Framework supports six scopes, four of which are
available only if you use a web-aware ApplicationContext. You can also create a custom scope.
The following table describes the supported scopes:
Scope Description
singleton (Default) Scopes a single bean definition to a single object instance for each Spring IoC
Scope Description
container.
prototype Scopes a single bean definition to any number of object instances.
request Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP
request has its own instance of a bean created off the back of a single bean definition. Only
valid in the context of a web-aware Spring ApplicationContext.
session Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the
context of a web-aware Spring ApplicationContext.
applicatio Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in
n the context of a web-aware Spring ApplicationContext.
websocket Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context
of a web-aware Spring ApplicationContext.
A thread scope is available but is not registered by default. For more information, see the documentation
for SimpleThreadScope. For instructions on how to register this or any other custom scope, see Using a Custom
Scope.
Spring’s concept of a singleton bean differs from the singleton pattern as defined in the Gang of Four (GoF) patterns
book. The GoF singleton hard-codes the scope of an object such that one and only one instance of a particular class
is created per ClassLoader. The scope of the Spring singleton is best described as being per-container and per-
bean. This means that, if you define one bean for a particular class in a single Spring container, the Spring
container creates one and only one instance of the class defined by that bean definition. The singleton scope is the
default scope in Spring. To define a bean as a singleton in XML, you can define a bean as shown in the following
example:
<bean id="accountService" class="[Link]"/>
<!-- the following is equivalent, though redundant (singleton scope is the default) -->
<bean id="accountService" class="[Link]"
scope="singleton"/>
Copied!
The Prototype Scope
The non-singleton prototype scope of bean deployment results in the creation of a new bean instance every time a
request for that specific bean is made. That is, the bean is injected into another bean or you request it through
a getBean() method call on the container. As a rule, you should use the prototype scope for all stateful beans and
the singleton scope for stateless beans.
The following diagram illustrates the Spring prototype scope:
(A data access object (DAO) is not typically configured as a prototype, because a typical DAO does not hold any
conversational state. It was easier for us to reuse the core of the singleton diagram.)
The following example defines a bean as a prototype in XML:
<bean id="accountService" class="[Link]"
scope="prototype"/>
Copied!
In contrast to the other scopes, Spring does not manage the complete lifecycle of a prototype bean. The container
instantiates, configures, and otherwise assembles a prototype object and hands it to the client, with no further
record of that prototype instance. Thus, although initialization lifecycle callback methods are called on all objects
regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called. The client
code must clean up prototype-scoped objects and release expensive resources that the prototype beans hold. To
get the Spring container to release resources held by prototype-scoped beans, try using a custom bean post-
processor which holds a reference to beans that need to be cleaned up.
In some respects, the Spring container’s role in regard to a prototype-scoped bean is a replacement for the
Java new operator. All lifecycle management past that point must be handled by the client. (For details on the
lifecycle of a bean in the Spring container, see Lifecycle Callbacks.)
[Link]
</listener-class>
</listener>
...
</web-app>
Copied!
Alternatively, if there are issues with your listener setup, consider using Spring’s RequestContextFilter. The filter
mapping depends on the surrounding web application configuration, so you have to change it as appropriate. The
following listing shows the filter part of a web application:
<web-app>
...
<filter>
<filter-name>requestContextFilter</filter-name>
<filter-class>[Link]</filter-
class>
</filter>
<filter-mapping>
<filter-name>requestContextFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
</web-app>
Copied!
DispatcherServlet, RequestContextListener, and RequestContextFilter all do exactly the same thing, namely bind the
HTTP request object to the Thread that is servicing that request. This makes beans that are request- and session-
scoped available further down the call chain.
Request scope
Consider the following XML configuration for a bean definition:
<bean id="loginAction" class="[Link]" scope="request"/>
Copied!
The Spring container creates a new instance of the LoginAction bean by using the loginAction bean definition for
each and every HTTP request. That is, the loginAction bean is scoped at the HTTP request level. You can change the
internal state of the instance that is created as much as you want, because other instances created from the
same loginAction bean definition do not see these changes in state. They are particular to an individual request.
When the request completes processing, the bean that is scoped to the request is discarded.
When using annotation-driven components or Java configuration, the @RequestScope annotation can be used to
assign a component to the request scope. The following example shows how to do so:
@RequestScope
@Component
public class LoginAction {
// ...
}
Copied!
Session Scope
Consider the following XML configuration for a bean definition:
<bean id="userPreferences" class="[Link]" scope="session"/>
Copied!
The Spring container creates a new instance of the UserPreferences bean by using the userPreferences bean
definition for the lifetime of a single HTTP Session. In other words, the userPreferences bean is effectively scoped at
the HTTP Session level. As with request-scoped beans, you can change the internal state of the instance that is
created as much as you want, knowing that other HTTP Session instances that are also using instances created from
the same userPreferences bean definition do not see these changes in state, because they are particular to an
individual HTTP Session. When the HTTP Session is eventually discarded, the bean that is scoped to that particular
HTTP Session is also discarded.
When using annotation-driven components or Java configuration, you can use the @SessionScope annotation to
assign a component to the session scope.
@SessionScope
@Component
public class UserPreferences {
// ...
}
Copied!
Application Scope
Consider the following XML configuration for a bean definition:
<bean id="appPreferences" class="[Link]" scope="application"/>
Copied!
The Spring container creates a new instance of the AppPreferences bean by using the appPreferences bean definition
once for the entire web application. That is, the appPreferences bean is scoped at the ServletContext level and stored
as a regular ServletContext attribute. This is somewhat similar to a Spring singleton bean but differs in two
important ways: It is a singleton per ServletContext, not per Spring ApplicationContext (for which there may be
several in any given web application), and it is actually exposed and therefore visible as a ServletContext attribute.
When using annotation-driven components or Java configuration, you can use the @ApplicationScope annotation to
assign a component to the application scope. The following example shows how to do so:
@ApplicationScope
@Component
public class AppPreferences {
// ...
}
Copied!
WebSocket Scope
Each WebSocket session has a map of attributes. The map is attached as a header to inbound client messages and
may be accessed from a controller method, as the following example shows:
@Controller
public class MyController {
@MessageMapping("/action")
public void handle(SimpMessageHeaderAccessor headerAccessor) {
Map<String, Object> attrs = [Link]();
// ...
}
}
Copied!
You can declare a Spring-managed bean in the websocket scope. You can inject WebSocket-scoped beans into
controllers and any channel interceptors registered on the clientInboundChannel. Those are typically singletons and
live longer than any individual WebSocket session. Therefore, you need to use a scope proxy mode for WebSocket-
scoped beans, as the following example shows:
@Component
@Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyBean {
@PostConstruct
public void init() {
// Invoked after dependencies injected
}
// ...
@PreDestroy
public void destroy() {
// Invoked when the WebSocket session ends
}
}
@Controller
public class MyController {
@MessageMapping("/action")
public void handle() {
// [Link] from the current WebSocket session
}
}
Copied!
As with any custom scope, Spring initializes a new MyBean instance the first time it is accessed from the controller
and stores the instance in the WebSocket session attributes. The same instance is subsequently returned until the
session ends. WebSocket-scoped beans have all Spring lifecycle methods invoked, as shown in the preceding
examples.
Autowiring:-
utowiring 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. To enable Autowiring in the Spring application we should use @Autowired annotation. 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 of Autowiring
Modes Description
1. No
This mode tells the framework that autowiring is not supposed to be done. It is the default mode used by Spring.
<bean id="state" class="[Link]">
<property name="name" value="UP" />
</bean>
<bean id="city" class="[Link]"></bean>
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="[Link]">
<property name="name" value="UP" />
</bean>
<bean id="city" class="[Link]" 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="[Link]">
<property name="name" value="UP" />
</bean>
<bean id="city" class="[Link]" 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="[Link]">
<property name="name" value="UP" />
</bean>
<bean id="city" class="[Link]" 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="[Link]">
<property name="name" value="UP" />
</bean>
<bean id="city" class="[Link]" autowire="autodetect"></bean>
Basically, there are 6 types of annotation available in the whole spring framework.
1. Spring Core Annotations
2. Spring Web Annotations
3. Spring Boot Annotations
4. Spring Scheduling Annotations
5. Spring Data Annotations
6. Spring Bean Annotations
Type 1: Spring Core Annotations
Spring annotations present in
the [Link] and [Link]
packages are commonly known as Spring Core annotations. We can divide them into two categories:
DI-Related Annotations
o @Autowired
o @Qualifier
o @Primary
o @Bean
o @Lazy
o @Required
o @Value
o @Scope
o @Lookup, etc.
Context Configuration Annotations
o @Profile
o @Import
o @ImportResource
o @PropertySource, etc.
A DI (Dependency Injection) Related Annotations
There are several ways to configure the Spring bean lifecycle callbacks as listed below.
1. The JSR-250 specification using @PostConstruct and @PreDestroy annotations. This is the recommended way.
2. Using the lifecycle callbacks in <bean/> or @bean declarations.
3. Using the default initialization and destroy methods.
4. Startup and Shutdown callbacks from the Lifecycle interface.
The below diagram shows the different stages spring bean goes through before it is ready to use. If you carefully observe the
diagram below, the last 3 phases are mentioned in the above discussion about several ways to specify bean lifecycle callbacks.
Initialization callbacks
The [Link] interface specifies a single method −
void afterPropertiesSet() throws Exception;
Thus, you can simply implement the above interface and initialization work can be done inside afterPropertiesSet() method
as follows −
public class ExampleBean implements InitializingBean {
public void afterPropertiesSet() {
// do some initialization work
}
}
In the case of XML-based configuration metadata, you can use the init-method attribute to specify the name of the
method that has a void no-argument signature. For example −
<bean id = "exampleBean" class = "[Link]" init-method = "init"/>
Destruction callbacks
The [Link] interface specifies a single method −
void destroy() throws Exception;
Thus, you can simply implement the above interface and finalization work can be done inside destroy() method as follows −
If you are using Spring's IoC container in a non-web application environment; for example, in a rich client desktop
environment, you register a shutdown hook with the JVM. Doing so ensures a graceful shutdown and calls the relevant
destroy methods on your singleton beans so that all resources are released.
It is recommended that you do not use the InitializingBean or DisposableBean callbacks, because XML configuration gives
much flexibility in terms of naming your method.
One of the most popular ways to create a spring bean is to define a bean in an XML configuration file something like this.
// Class
public class Student {
// Method
public void displayInfo()
{
// Print statement
[Link]("Student Name is " + studentName
+ " and Roll Number is " + id);
}
}
Now let’s create an XML file named [Link] file in the project classpath. And inside this [Link] file, we have to
define our Student bean something like this. And that’s it. In this way, you can create beans in spring.
</bean>
</beans>
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide
supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It
does not change the action of the compiled program. @Component is an annotation that allows Spring to automatically
detect the custom beans.
Example: Suppose we have already a Java project and all the Spring JAR files are imported into that project. Now let’s
create a simple class named College and inside the class, we have a simple method. Below is the code for
the [Link] file.
A. File: [Link]
// Java Program to Illustrate College Class
package ComponentAnnotation;
// Class
public class College {
// Method
public void test()
{
// Print statement
// whenever this method is called
[Link]("Test College Method");
}
}
Now let’s create a Bean for this class. So we can use @Component annotation for doing the same task. So we can modify
our [Link] file something like this. And that’s it.
B. [Link]
// Java Program to Illustrate College Class
package ComponentAnnotation;
@Component("collegeBean")
// Class
public class College {
// Method
public void test()
{
// Print statement
[Link]("Test College Method");
}
}
One of the most important annotations in spring is the @Bean annotation which is applied on a method to specify that it
returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes
methods.
Suppose we have already a Java project and all the Spring JAR files are imported into that project. Now let’s create a
simple class named College and inside the class, we have a simple method. Below is the code for the [Link] file.
A. [Link]
package BeanAnnotation;
import [Link];
import [Link];
import [Link];
@Configuration
public class CollegeConfig {
Spring Boot: - Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can
"just run".
We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot
applications need minimal Spring configuration.
If you’re looking for information about a specific version, or instructions about how to upgrade from an earlier release, check out the project
release notes section on our wiki.
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
Spring Boot Build Systems:-In Spring Boot, choosing a build system is an important task. We
recommend Maven or Gradle as they provide a good support for dependency management. Spring does not support well
other build systems.
Dependency Management
Spring Boot team provides a list of dependencies to support the Spring Boot version for its every release. You do
not need to provide a version for dependencies in the build configuration file. Spring Boot automatically
configures the dependencies version based on the release. Remember that when you upgrade the Spring Boot
version, dependencies also will upgrade automatically.
Note − If you want to specify the version for dependency, you can specify it in your configuration file. However,
the Spring Boot team highly recommends that it is not needed to specify the version for dependency.
Maven Dependency
For Maven configuration, we should inherit the Spring Boot Starter parent project to manage the Spring Boot
Starters dependencies. For this, simply we can inherit the starter parent in our [Link] file as shown below.
<parent>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>[Link]</version>
</parent>
We should specify the version number for Spring Boot Parent Starter dependency. Then for other starter
dependencies, we do not need to specify the Spring Boot version number. Observe the code given below −
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
Learn Spring Boot in-depth with real-world projects through our Spring Boot certification course. Enroll and
become a certified expert to boost your career.
Gradle Dependency
We can import the Spring Boot Starters dependencies directly into [Link] file. We do not need Spring Boot
start Parent dependency like Maven for Gradle. Observe the code given below −
buildscript {
ext {
springBootVersion = '[Link]'
}
repositories {
mavenCentral()
}
dependencies {
classpath("[Link]:spring-boot-gradle-plugin:${springBootVersion}")
}
}
Similarly, in Gradle, we need not specify the Spring Boot version number for dependencies. Spring Boot
automatically configures the dependency based on the version.
dependencies {
compile('[Link]:spring-boot-starter-web')
}
Spring Boot Code Structure:- There is no specific layout or code structure for Spring Boot
Projects. However, there are some best practices followed by developers that will help us too. You can divide your project
into layers like service layer, entity layer, repository layer,, etc. You can also divide the project into modules. For example,
the parent project has two child modules. The first module is for the data layer and the second module is for the web layer.
You can also divide the project into features.
Note: Avoid Default Package
It is. because a class is said to be in a default package when it does not include a package declaration. It is not a best
practice to include a class in the default package. It is because Spring scans the classes in packages and sub-packages
mentioned in the annotations like @ComponentScan, @EntityScan, @SpringBootApplication etc.
Note: It is recommended to use Java’s package naming conventions with a reverse domain name. For
example, [Link].
Main Application Class
It is recommended to place the Main Application class in the root package with annotations
like @SpringBootApplication or @ComponentScan or @EnableAutoConfiguration. It allows the Spring to scan all
classes in the root package and sub-packages. For example, if you are writing a JPA application similar to the below layout
example, the [Link] is placed in the root package and all Customer-related classes in the sub-
package [Link] and Order related classes in the [Link].
Layout Structure is as follows:
Let us discuss two approaches that are typically used by most developers to structure their spring boot projects.
1. Structure by Feature
2. Structure by Layer
Structure 1: By feature
In this approach, all classes pertaining to a certain feature are placed in the same package. The structure by feature looks
is shown in below example
Example
com
+- gfg
+- demo
+- [Link]
|
+- customer
| +- [Link]
| +- [Link]
| +- [Link]
| +- [Link]
|
+- order
+- [Link]
+- [Link]
+- [Link]
+- [Link]
The advantages of this structure is as follows:
Find a class to be modified is easy.
By deleting a particular sub-package, all the classes related to a certain feature can be deleted.
Testing and Refactoring is easy.
Features can be shipped separately.
Structure 2: By Layer
Another way to place the classes is by layer i.e; all controllers can be placed in controllers package and services under
services package and all entities under domain or model etc.
Example
com
+- gfg
+- demo
+- [Link]
|
+- domain
| +- [Link]
| +- [Link]
|
+- controllers
| +- [Link]
| +- [Link]
|
+- services
| +- [Link]
| +- [Link]
|
+- repositories
+- [Link]
+- [Link]
Though the above structure looks feasible and easy to locate classes by a layer. It has few disadvantages when compared
to Structure by Feature.
Features or Modules cannot be shipped separately.
Hard to locate a class pertaining to a certain feature.
Code Refactoring on a certain feature is difficult since the feature classes located in every layer.
It causes merge conflicts among developers using GitHub, BitBucket, etc. for Collaboration.
Now let us wrap up by acquiring the location of [Link]. as in both the structures proposed above we have
seen that the [Link] is placed in the root package with @SpringBootApplication annotation. It s as
shown below in as a sample example which is as follows:
Example
@SpringBootApplication
public class MyApplication {
Spring Boot Runners:- Application Runner and Command Line Runner interfaces lets you to
execute the code after the Spring Boot application is started. You can use these interfaces to perform any actions
immediately after the application has started. This chapter talks about them in detail.
Application Runner
Application Runner is an interface used to execute the code after the Spring Boot application started. The example given
below shows how to implement the Application Runner interface on the main class file.
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@SpringBootApplication
public class DemoApplication implements ApplicationRunner {
public static void main(String[] args) {
[Link]([Link], args);
}
@Override
public void run(ApplicationArguments arg0) throws Exception {
[Link]("Hello World from Application Runner");
}
}
Command Line Runner is an interface. It is used to execute the code after the Spring Boot application started. The example
given below shows how to implement the Command Line Runner interface on the main class file.
package [Link];
import [Link];
import [Link];
import [Link];
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
public static void main(String[] args) {
[Link]([Link], args);
}
@Override
public void run(String... arg0) throws Exception {
[Link]("Hello world from Command Line Runner");
}
}
Logger:-Logger in Spring Boot plays a vital role in Spring Boot applications for recording information, actions,
and events within the app. It is also used for monitoring the performance of an application, understanding the behavior of
the application, and recognizing the issues within the application. Spring Boot offers flexible logging capabilities by
providing various logging frameworks and also provides ways to manage and configure the logs.
Why to use Spring Boot – Logging?
A good logging infrastructure is necessary for any software project as it not only helps in understanding what’s going on
with the application but also to trace any unusual incident or error present in the project. This article covers several ways in
which logging can be enabled in a spring boot project through easy and simple configurations. Let’s first do the initial setup
to explore each option in more depth.
Elements of Logging Framework
Logger: It captures the messages.
Formatter: It formats the messages which are captured by loggers.
Handler: It prints messages on the console, stores them in a file or sends an email, etc.
Java provides several logging frameworks, some of which are:
1. Logback Configuration logging
2. Log4j2 Configuration logging
3. Logging with Lombok
4. @Slf4j and @CommonsLog
It does not define the standard message exchange format. We can build REST services with both XML and JSON. JSON is
more popular format with REST. The key abstraction is a resource in REST. A resource can be anything. It can be
accessed through a Uniform Resource Identifier (URI). For example:
The resource has representations like XML, HTML, and JSON. The current state capture by representational resource. When
we request a resource, we provide the representation of the resource. The important methods of HTTP are:
o GET: It reads a resource.
o PUT: It updates an existing resource.
o POST: It creates a new resource.
o DELETE: It deletes the resource.
For example, if we want to perform the following actions in the social media application, we get the corresponding results.
POST /users: It creates a user.
GET /users/{id}: It retrieves the detail of a user.
GET /users: It retrieves the detail of all users.
DELETE /users: It deletes all users.
DELETE /users/{id}: It deletes a user.
GET /users/{id}/posts/post_id: It retrieve the detail of a specific post.
POST / users/{id}/ posts: It creates a post of the user.
Further, we will implement these URI in our project.
HTTP also defines the following standard status code:
o 404: RESOURCE NOT FOUND
o 200: SUCCESS
o 201: CREATED
o 401: UNAUTHORIZED
o 500: SERVER ERROR
Rest Controller:- RestController is used for making restful web services with the help of the
@RestController annotation. This annotation is used at the class level and allows the class to handle the requests made
by the client. Let’s understand @RestController annotation using an example. The RestController allows to handle all
REST APIs such as GET, POST, Delete, PUT requests.
Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also
provides various different features for the projects expressed in a metadata model. This model allows us to configure the
list of dependencies that are supported by JVM. Here, we will create the structure of an application using a spring initializer
and then use an IDE to create a sample GET route. Therefore, to do this, the following steps are followed sequentially as
follows.
Project: Maven
Language: Java
Spring Boot: 2.2.8
Packaging: JAR
Java: 8
Dependencies: Spring Web
Step 2: Click on Generate which will download the starter project
Step 3: Extract the zip file. Now open a suitable IDE and then go to File > New > Project from existing sources > Spring-
boot-app and select [Link]. Click on import changes on prompt and wait for the project to sync as pictorially depicted
below as follows:
Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while
creating the project.
Step 4: Go to src > main > java > [Link], create a java class with the name Controller and add the
annotation @RestController and other class named as Details.
Now /home is the URI for which this controller will be used. This concept is very similar to servlet context of a web application.
2. @RequestMapping with Method: We can use it with method to provide the URI pattern for which handler method will be used. For
example:
@RequestMapping(value="/method0")
@ResponseBody
public String method0(){
return "method0";
}
Above annotation can also be written as @RequestMapping("/method0"). On a side note, I am using @ResponseBody to send
the String response for this web request, this is done to keep the example simple. Like I always do, I will use these methods in
Spring MVC application and test them with a simple program or script.
3. @RequestMapping with Multiple URI: We can use a single method for handling multiple URIs, for example:
@RequestMapping(value={"/method1","/method1/second"})
@ResponseBody
public String method1(){
return "method1";
}
If you will look at the source code of RequestMapping annotation, you will see that all of it’s variables are arrays. We can create
String array for the URI mappings for the handler method.
4. @RequestMapping with HTTP Method: Sometimes we want to perform different operations based on the HTTP method used,
even though request URI remains same. We can use @RequestMapping method variable to narrow down the HTTP methods for
which this method will be invoked. For example:
@RequestMapping(value="/method2", method=[Link])
@ResponseBody
public String method2(){
return "method2";
}
@RequestMapping(value="/method3", method={[Link],[Link]})
@ResponseBody
public String method3(){
return "method3";
}
5. @RequestMapping with Headers: We can specify the headers that should be present to invoke the handler method. For example:
@RequestMapping(value="/method4", headers="name=pankaj")
@ResponseBody
public String method4(){
return "method4";
}
Path Variable :-The @PathVariable annotation is used to extract data from the URL path. It allows you to
define placeholders in your request mapping URL and bind those placeholders to method parameters. Let’s consider an
example where you have a REST API endpoint for retrieving a user’s details by their ID:
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{userId}")
public ResponseEntity<User> getUserDetails(@PathVariable Long userId) {
// Implementation to fetch user details based on the provided userId
// ...
return [Link](user);
}
}
In the above code, the @PathVariable annotation is used to extract the userId from the URL path. The {userId} placeholder
is defined in the @GetMapping annotation’s URL mapping. The value of the {userId} placeholder will be extracted and
passed as the userId method parameter. When a request is made to /users/123, the value 123 will be passed to the
getUserDetails method as the userId parameter. You can then use this ID to fetch the user details from a database or any
other data source.
Request Parameter:- The RequestParam annotation is used to extract data from the query
parameters in the request URL. Query parameters are the key-value pairs that appear after the ? in a URL. Let’s consider
an example where you have a REST API endpoint for searching users based on a query parameter:
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/search")
public ResponseEntity<List<User>> searchUsers(@RequestParam("name")
String name) {
// Implementation to search users based on the provided name
// ...
return [Link](users);
}
}
In the above code, the @RequestParam annotation is used to extract the name parameter from the query parameters. The
name parameter is specified as an argument of the @RequestParam annotation. When a request is made to
/users/search?name=John, the value John will be passed to the searchUsers method as the name parameter. You can
then use this parameter to perform a search operation based on the provided name.
The CRUD operation can be defined as user interface conventions that allow view, search, and modify information through
computer-based forms and reports. CRUD is data-oriented and the standardized use of HTTP action verbs. HTTP has a
few important verbs.
CRUD operations are at the foundation of the most dynamic websites. Therefore, we should differentiate CRUD from
the HTTP action verbs.
Suppose, if we want to create a new record, we should use HTTP action verb POST. To update a record, we should use
the PUT verb. Similarly, if we want to delete a record, we should use the DELETE verb. Through CRUD operations, users
and administrators have the right to retrieve, create, edit, and delete records online.
We have many options for executing CRUD operations. One of the most efficient choices is to create a set of stored
procedures in SQL to execute operations.
The CRUD operations refer to all major functions that are implemented in relational database applications. Each letter of
the CRUD can map to a SQL statement and HTTP methods.
Build Web Applications:-This guide provides a sampling of how Spring Boot helps you accelerate
application development. As you read more Spring Getting Started guides, you will see more use cases for Spring Boot. This guide is meant
to give you a quick taste of Spring Boot. If you want to create your own Spring Boot-based project, visit Spring Initializr, fill in your project
details, pick your options, and download a bundled up project as a zip file.
What You Will build
You will build a simple web application with Spring Boot and add some useful services to it.
What You Need
About 15 minutes
A favorite text editor or IDE
Java 17 or later
Gradle 7.5+ or Maven 3.5+
You can also import the code straight into your IDE:
Spring Tool Suite (STS)
IntelliJ IDEA
VSCode
How to complete this guide
Like most Spring Getting Started guides, you can start from scratch and complete each step or you can bypass basic setup steps that are
already familiar to you. Either way, you end up with working code.
To start from scratch, move on to Starting with Spring Initializr.
To skip the basics, do the following:
Download and unzip the source repository for this guide, or clone it using Git: git
clone [Link]
cd into gs-spring-boot/initial
Jump ahead to Create a Simple Web Application.
When you finish, you can check your results against the code in gs-spring-boot/complete .