0% found this document useful (0 votes)
2 views44 pages

File 6048 Oopsjunit51

The document provides an overview of the Spring Framework and Spring Boot, detailing their functionalities, including Inversion of Control (IoC), Dependency Injection (DI), and Aspect-Oriented Programming (AOP). It explains the core concepts, types of dependency injection, bean scopes, autowiring, and various annotations used within the framework. Additionally, it covers the lifecycle of beans and configuration styles, emphasizing the importance of these features in developing Java-based applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views44 pages

File 6048 Oopsjunit51

The document provides an overview of the Spring Framework and Spring Boot, detailing their functionalities, including Inversion of Control (IoC), Dependency Injection (DI), and Aspect-Oriented Programming (AOP). It explains the core concepts, types of dependency injection, bean scopes, autowiring, and various annotations used within the framework. Additionally, it covers the lifecycle of beans and configuration styles, emphasizing the importance of these features in developing Java-based applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

UNIT-5

(SPRING FRAMEWORK AND SPRING BOOT)

What is Spring Framework (Spring)?


Spring Framework (Spring) is an open source software development
framework that provides infrastructure support for building Java-based
applications on any deployment platform.

Released in June 2003 by Rod Johnson under the Apache 2.0 license, Spring
Framework is hosted by SourceForge.

Basics of Spring Framework

The Spring Framework is a comprehensive framework designed for

enterprise Java development. It offers a range of tools and libraries to

support various aspects of application development, from dependency

injection to transaction management. This section covers the core concepts


and foundational aspects of Spring, helping you understand the building

blocks of the framework.

Core Spring

Core Spring focuses on the fundamental principles of Inversion of Control

(IoC) and Dependency Injection (DI). These concepts are crucial for

decoupling components and managing object lifecycles.

Inversion of Control
Inversion of Control (IoC) is a design principle in the

Spring Framework (and other frameworks) that shifts

the responsibility for managing object lifecycles and

dependencies from the application code to the

framework. In Spring, IoC is achieved through the

Dependency Injection (DI) mechanism.


Ioc in Spring

How Inversion of Control Works in Spring


1. Container Responsibility: Spring provides an

IoC container that is responsible for managing

the lifecycle of beans (objects) and their

dependencies. Beans are configured

declaratively (via XML or annotations) or

programmatically (via Java configuration).

2. Dependency Injection: Spring injects the

required dependencies into beans either at

runtime or during initialization, without the


bean explicitly instantiating or locating its

dependencies. This can be done using:

● Constructor Injection: Dependencies are

provided through the class constructor.

● Setter Injection: Dependencies are set using

setter methods.

● Field Injection: Dependencies are injected

directly into fields using annotations (e.g.,

@Autowired).
Dependency Injection
Dependency Injection is the main functionality provided by Spring

IOC(Inversion of Control). The Spring-Core module is responsible for

injecting dependencies through either Constructor or Setter methods. The

design principle of Inversion of Control emphasizes keeping the Java classes

independent of each other and the container frees them from object creation

and maintenance. These classes, managed by Spring, must adhere to the

standard definition of Java-Bean. Dependency Injection in Spring also

ensures loose coupling between the classes.

Need for Dependency Injection:

Suppose class One needs the object of class Two to instantiate or operate a

method, then class One is said to be dependent on class Two. Now though it

might appear okay to depend on a module on the other, in the real world, this

could lead to a lot of problems, including system failure. Hence such

dependencies need to be avoided. Spring IOC resolves such dependencies

with Dependency Injection, which makes the code easier to test and reuse .

Loose coupling between classes can be possible by defining interfaces for

common functionality and the injector will instantiate the objects of required
implementation. The task of instantiating objects is done by the container

according to the configurations specified by the developer.

Types of Spring Dependency Injection

There are two primary types of Spring Dependency Injection:

1. Setter Dependency Injection (SDI):

Setter DI involves injecting dependencies via setter methods. To configure

SDI, the @Autowired annotation is used along with setter methods, and the

property is set through the <property> tag in the bean configuration file.

2. Constructor Dependency Injection (CDI):

Constructor DI involves injecting dependencies through constructors. To

configure CDI, the <constructor-arg> tag is used in the bean configuration

file.

AOP
Aspect-Oriented Programming (AOP) in Spring Boot 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. In this article, we will explore AOP concepts, Spring
AOP implementation, and real-world examples to help you integrate AOP
into your Spring Boot projects effectively.

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:

○ Before: Executed before the method call.

○ After: Executed after the method call, regardless of

its outcome.

○ AfterReturning: Executed after the method returns a

result, but not if an exception occurs.

○ Around: Surrounds the method execution, allowing

you to control the method execution and its result.

○ AfterThrowing: Executed if the method throws an

exception.

Dominant AOP Frameworks


● AspectJ: A powerful and mature AOP framework that supports

compile-time and load-time weaving. It offers full AOP support with

its own syntax and tools.

● JBoss AOP: Part of the JBoss application server, offering integration

with Java EE applications.

● Spring AOP: A simpler, proxy-based framework that integrates

with the Spring Framework, using XML configurations or

annotations to define aspects and pointcuts.



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


Bean scopes in Spring Boot define the lifecycle and visibility of
Spring-managed beans. They determine how instances of a particular
bean are created,managed, and shared within the application context.

In Spring Boot, beans are managed objects within the

Inversion of Control (IoC) container, and their scope

determines their lifecycle and visibility.

Choosing the appropriate scope depends on the nature of

the bean and its intended usage within the application.

Spring Boot provides several bean scopes, including:

○ Singleton: The default scope. A singleton bean is created

only once, and the same instance is shared across all


requests. It remains in the application context until the
application shuts down.
○ Prototype: A new instance of the prototype bean is created

each time it is requested. It allows multiple instances of the


same bean to coexist within the application.
○ Request: A new instance of the request-scoped bean is

created for eacH HTTP request. It is useful when you want


to store data specific to a single request, such as user
session information.
○ Session: A new instance of the session-scoped bean is

created for each user session. It maintains the state


specific to a user's session across multiple requests.
○ Application: A new instance of the application-scoped bean

is created once for the entire application. It is shared


across all requests and sessions.
○ WebSocket: A new instance of the web socket-scoped

bean is created for each WebSocket session.

Auto-wiring in Spring is a feature that enables the Spring framework to


automatically resolve and inject dependencies between beans. It eliminates
the need for explicit configuration of bean relationships, reducing boilerplate
code and making applications easier to manage.

How Autowiring is Achieved:

@Autowired Annotation:
The primary way to enable autowiring is using the @Autowired annotation. It
can be applied to:
● Fields: Spring injects a bean directly into the field.
● Constructors: Spring injects beans into the constructor parameters.
● Setter Methods: Spring injects beans through setter methods.
Types of Autowiring:

byType:
Spring searches for a bean of the same type as the dependency. This is the most
common approach.
byName:
Spring searches for a bean with a name that matches the dependency's field or
parameter name.
constructor:
Spring uses the constructor to resolve dependencies.
autodetect:
Spring tries to resolve dependencies by constructor first, and if no match is found, it
tries by type.

Benefits of Autowiring:

Reduced Configuration:
Eliminates the need for explicit XML or Java configuration for dependency
injection.
Improved Readability:
Makes code cleaner and easier to understand by removing dependency wiring
details.
Increased Development Speed:
Simplifies the development process by automating dependency resolution.
Flexibility:
Allows for easy modification of dependencies without changing the wiring
configuration.

Spring Annotations are a form of metadata that provides data about


a program. Annotations are used to provide supplemental information about
a program. They do not have a direct effect on the operation of the code they
annotate, nor do they change the action of the compiled program. In this
article, we will discuss the main types of annotations available in the Spring
Framework with examples.

Types of Spring Framework Annotations


● Spring Core Annotations

● Spring Web Annotations

● Spring Boot Annotations

● Spring Scheduling Annotations

● Spring Data Annotations

● Spring Bean Annotations

1. Spring Core Annotations


Spring annotations are present in the
org.springframework.beans.factory.annotation and
org.springframework.context.annotation packages. These annotations can
be divided into two categories

Dependency Injection(DI)-Related Annotations

@Autowired: This annotation is applied to fields, setter methods, and


constructors. It injects object dependency implicitly.

● @Qualifier: This annotation specifies which bean to inject when

multiple beans of the same type are available.


● @Primary: This annotation marks a bean as the default one to inject

when multiple candidates are present.

● @Bean: This annotation defines a Spring bean explicitly in a

configuration class.

● @Scope: This annotation specifies the scope of a Spring bean (e.g.,

singleton, prototype).

● @Value: This annotation injects values into fields from property

files.

● @Lazy: This annotation indicates that the bean should be lazily

initialized.

● @Required: This annotation marks a property as required for

injection.

● @Lookup: This annotation is used for method injection with

prototype-scoped beans.

Context Configuration Annotations

@Profile: This annotation is used to indicate that a @Component class or a


@Bean method should only be used when a specific profile is active.

Example:

@Component
@Profile("developer")
public class Employee {}
● @Import: This annotation imports other configuration classes.

● @ImportResources: This annotation loads Spring XML configuration

files.

● @PropertySource: This annotation specifies the location of property

files for the application context.

2. Spring Web Annotations


Spring Web annotations are present in the
org.springframework.web.bind.annotation package. Some of the commonly
used annotations in this category are:

@Controller: This annotation marks a class as a Spring MVC controller. It is


used with @RequestMapping to handle web requests.

● @RequestMapping: This annotation maps HTTP requests to

handler methods in the controller.

● @RequestBody: This annotation binds the body of the HTTP

request to a Java object.

● @PathVariable: This annotation extracts values from the URI

template.

● @RequestParam: This annotation extracts query parameters from

the URL.

● @ResponseBody: This annotation indicates that the return value of

the method should be used as the response body.


● @ExceptionHandler: This annotation is used to handle exceptions

thrown by request-handling methods.

● @ResponseStatus: This annotation specifies the HTTP status code

for the response.

● @RestController: This annotation is a combination of @Controller

and @ResponseBody, used for RESTful web services.

● @ModelAttribute: This annotation binds a method parameter or

method return value to a named model attribute.

● @CrossOrigin: This annotation enables cross-origin resource

sharing (CORS) for specific handler methods or controller classes.

3. Spring Boot Annotations


Spring Boot annotations are present in the
org.springframework.boot.autoconfigure and
org.springframework.boot.autoconfigure.condition packages. Some of the
commonly used annotations in this category are:

@SpringBootApplication: This annotation is used to mark the main class of


a Spring Boot application. It encapsulates @Configuration,
@EnableAutoConfiguration, and @ComponentScan annotations with their
default attributes.

● @EnableAutoConfiguration: This annotation enabled Spring Boot’s

auto-configuration mechanism.
● @ConditionalOnClass: This annotation configures a bean only if a

specified class is present on the classpath.

● @ConditionalOnMissingBean: This annotation configures a bean

only if a specified bean is not already present in the application

context.

4. Spring Scheduling Annotations


Spring Scheduling annotations are present in the
org.springframework.scheduling.annotation package. Some of the
commonly used annotations in this category are:

● @EnableAsync: This annotation enables asynchronous processing

in Spring.

● @EnableScheduling: This annotation enables scheduling in Spring.

● @Async: This annotation marks a method to be executed

asynchronously.

● @Scheduled: This annotation marks a method to be executed on a

fixed schedule.

5. Spring Data Annotations


Spring Data annotations provide an abstraction over data storage
technologies. Some of the commonly used annotations in this category are:

@Transactional: This annotation marks a method or class as transactional.


@Id: This annotation marks a field in a model class as the primary key.

● @Query: This annotation defines custom queries for repositories.

● @Procedure: This annotation marks a method for calling a stored

procedure.

● @Lock: This annotation specifies locking behavior for methods.

● @Modifying: This annotation marks a query as modifying (e.g., for

update or delete operations).

● @EnableJpaRepositories: This annotation enables JPA repositories

in a Spring application.

● @Document (MongoDB): This annotation marks a class as a

MongoDB document.

● @Field (MongoDB): This annotation specifies a field in a MongoDB

document.

6. Spring Bean Annotations


Spring Bean annotations are used to configure beans in a Spring container.
Some of the commonly used annotations in this category are:

● @ComponentScan: This annotation is used to specify the base

packages for scanning components.

● @Configuration: This annotation indicates that the class can be

used by the Spring IoC container as a source of bean definitions.


● @Stereotype: This annotation is used to automatically register

beanS in the spring context based on their roles.

Bean Life Cycle


The lifecycle of a bean in Spring refers to the sequence of events that occur

from the moment a bean is instantiated until it is destroyed. Understanding

this lifecycle is important for managing resources effectively and ensuring

that beans are properly initialized and cleaned up.

Bean life cycle is managed by the spring container. When we run the

program, 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. 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.

Bean Life Cycle Phases

The lifecycle of a Spring bean consists of the following phases, which are
listed below
● Container Started: The Spring IoC container is initialized.

● Bean Instantiated: The container creates an instance of the bean.


● Dependencies Injected: The container injects the dependencies into

the bean.

● Custom init() method: If the bean implements InitializingBean or has

a custom initialization method specified via @PostConstruct or init-

method.

● Bean is Ready: The bean is now fully initialized and ready to be

used.

● Custom utility method: This could be any custom method you have

defined in your bean.

● Custom destroy() method: If the bean implements DisposableBean

or has a custom destruction method specified via @PreDestroy or

destroy-method, it is called when the container is shutting down.


Bean Configuration styles
In Java, particularly within the Spring Framework, there are several ways to
configure beans, which are objects managed by the Spring container. These
configurations determine how beans are created, initialized, and wired
together. Here's a breakdown of the common approaches:

XML-based Configuration

How it works:
Bean definitions are specified in an XML file, typically named
applicationContext.xml. This file contains <bean> elements, each defining
a bean's class, properties, and dependencies.
Pros:
Centralized configuration, good for legacy projects, clear separation of
configuration from code.
Cons:
Verbose, which can be harder to maintain for complex applications, lacks compile-
time safety.

Annotation-based Configuration

● How it works: Uses annotations directly on Java classes and methods to define
beans. Key annotations include:
● @Component: Marks a class as a Spring-managed component.
● @Service, @Repository, @Controller: Specialized forms of
@Component for specific layers.
● @Bean: Used on methods within @Configuration classes to define
beans.
● @Autowired: Injects dependencies into fields, constructors, or methods.
● @Configuration: Indicates that a class provides bean definitions
● Pros: Concise, reduces boilerplate, easy to refactor, leverages compile-time
safety.
● Cons: Can be less clear for complex configurations, might require more
scanning.

Java-based Configuration

How it works:
Uses @Configuration classes and @Bean methods to define beans
programmatically. This approach allows for more complex logic and conditional
bean creation.
Pros:
Type-safe, supports refactoring, integrates well with IDEs, allows for dynamic
bean definitions.
Cons:
Can be more verbose than annotation-based configuration, might require writing
more code.

Spring Boot
Spring Boot is a Java framework that makes it easier to create and run Java

applications. It simplifies the configuration and setup process, allowing

developers to focus more on writing code for their applications.

This Spring Boot Tutorial is a comprehensive guide that covers both basic

and advanced concepts of the Spring Framework. It is designed for beginners

as well as professionals.

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.

Maven:

● Uses a pom.xml file for dependency management and configuration.


● Widely used and well-supported in the Java ecosystem.
● Provides a structured approach to project building.

Gradle:
● Uses a build.gradle file for dependency management and configuration.
● Offers more flexibility and faster build times compared to Maven.
● Supports both Groovy and Kotlin for build scripts.

Dependency Management:

● Spring Boot provides a curated list of dependencies, eliminating the need to


specify versions for supported libraries.
● The spring-boot-dependencies Bill of Materials (BOM) is used by both
Maven and Gradle to manage dependency versions.
● Developers can override Spring Boot's recommended versions if needed.

Other Build Systems:

● While not as well-supported, Spring Boot can also work with other build systems
like Ant.
● spring-boot-antlib is a module that helps Ant create executable JARs.

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.

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.
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
+- MyApplication.java
|
+- customer
| +- Customer.java
| +- CustomerController.java
| +- CustomerService.java
| +- CustomerRepository.java
|
+- order
+- Order.java
+- OrderController.java
+- OrderService.java
+- OrderRepository.java

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
+- MyApplication.java
|
+- domain
| +- Customer.java
| +- Order.java
|
+- controllers
| +- OrderController.java
| +- CustomerController.java
|
+- services
| +- CustomerService.java
| +- OrderService.java
|
+- repositories
+- CustomerRepository.java
+- OrderRepository.java

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 MainApplication.java. as in
both the structures proposed above we have seen that the
MainApplication.java 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 {

public static void main(String[] args) {


SpringApplication.run(MyApplication.class, args);
}

Spring Boot Runners


Spring Boot Runners are interfaces that allow you to execute code after the
Spring Boot application has started. They are typically used to perform
initialization tasks, such as loading data into a database, setting up
configurations, or running background processes.
Two important interfaces in Spring Boot are CommandLineRunner and
ApplicationRunner
You can use these interfaces to perform any actions immediately after the
application has started.
Command Line Runner: CommandLineRunner is a
functional interface with a single method run(String… args).
It allows you to run additional code before the application
fully starts. It’s useful for tasks that need to be performed
after all the Spring beans are initialized.
If you only need simple access to the raw command-line
arguments and don’t need to differentiate between option
and non-option arguments.
Command Line Runner was introduced in Spring-Boot 1.0
Version. It’s a legacy runner.
@Component
public class MyCommandLineRunner implements CommandLineRunner {

@Override

public void run(String... args) throws Exception {

System.out.println("Executing CommandLineRunner...");

// Incorporate your initialization logic here

Application Runner: ApplicationRunner is similar to CLR


but provides a bit more flexibility with the
ApplicationArguments interface. The
run(ApplicationArguments args) method provides access to
both the raw and parsed command-line arguments. This can
be particularly useful when you need to process the
application arguments in a structured manner.

It is a new type of runner added in Spring boot 1.3 which


makes it easy to access arguments.

This will separate Option Arguments (as Map<String,


List<String>>) and Non-Option Arguments
(<List<String>).
@Component

public class MyApplicationRunner implements ApplicationRunner {

@Override

public void run(ApplicationArguments args) throws Exception {

System.out.println("Executing ApplicationRunner...");

// Incorporate your initialization logic here

}
}

Key Differences :

Method Signature: CommandLineRunner uses run(String…


args), whereas ApplicationRunner uses
run(ApplicationArguments args).

Arguments Handling: ApplicationRunner provides the


ApplicationArguments object, which offers more detailed
handling of command-line arguments, including access to
both option and non-option arguments.

Spring Boot Logging:-


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

Log Levels

Levels Usage
Error It is used for non-recoverable error.

Warning It is used for recoverable error.

Info It is used for audit purpose.

Debug It is used for investigation.

Trace It is used for detailed investigation.

Why Logging Matters

● Monitoring: Track application health and performance.


● Troubleshooting: Diagnose and fix issues.
● Auditing: Record user activities and events.

RESTful Web Services


RESTful Web Services REST stands for REpresentational State Transfer. It
was developed by Roy Thomas Fielding, one of the principal authors of the
web protocol HTTP. Consequently, REST was an architectural approach
designed to make the optimum use of the HTTP protocol. It uses the
concepts and verbs already present in HTTP to develop web services. This
made REST incredibly easy to use and consume, so much so that it is the go-
to standard for building web services today.
A resource can be anything, it can be accessed through a URI (Uniform
Resource Identifier). Unlike SOAP, REST does not have a standard
messaging format. We can build REST web services using many
representations, including both XML and JSON, although JSON is the more
popular option. An important thing to consider is that REST is not a standard
but a style whose purpose is to constrain our architecture to a client-server
architecture and is designed to use stateless communication protocols like
HTTP.
@RestController:
This annotation is used to handle REST APIs, such as GET, PUT, POST, and
DELETE, and create RESTful web services using Spring MVC. It combines the
functionality of @Controller and @ResponseBody.

Steps to Build a RESTful Web Service

Set up a Spring Boot project:


You can use Spring Initializer to generate a basic project structure. Include the
"Spring Web" dependency.
Create Controllers:
Use the @RestController annotation to define a controller class and use
annotations like @RequestMapping, @GetMapping, @PostMapping,
@PutMapping, and @DeleteMapping to define the URI mappings for your API
endpoints.
Implement Service Layer:
Create a service class to handle the business logic of your application,
separating it from the controller logic.
Create Data Access Layer:
Implement a data access layer using Spring Data JPA to interact with a
database.
Test the service:
Use tools like Postman to send HTTP requests to your API endpoints and verify
the responses.

The main methods of HTTP we build web services for are:


1. GET: Reads existing data.

2. PUT: Updates existing data.

3. POST: Creates new data.

4. DELETE: Deletes the data.

REST API Security

Modern RESTful APIs should follow the below security practices:


● Authentication and Authorization: Use OAuth 2.0 or JWT-based

authentication.

● Rate Limiting: Implement API rate limiting to prevent abuse.

● Input Validation: Sanitize input to prevent SQL injection and XSS

attacks.

● HTTPS Enforcement: Ensure secure communication by enforcing

HTTPS.
Advantages of RESTful Web Services

Some of the primary advantages of using RESTful web services are,


● Easy to Build: REST APIs are simpler to build than a corresponding

SOAP API. Hence, REST is the better choice if we want to develop

APIs quickly.

● Independent: Since the client and server are decoupled in RESTful

web services, it allows for independent development across

projects.

● Scalability: Stateless communication and a replicated repository

provide a high level of scalability. Compared to SOAP, scaling up an

existing website is easier with the REST web services.

● Layered System: REST web services have their application divided

into multiple layers forming a hierarchy. It makes the application

both modular and scalable.

RestController
This annotation is used at the class level and allows the class to handle the

requests made by the client. The RestController allows the class to handle

REST API requests such as GET, POST, PUT, and DELETE by automatically

serializing responses to JSON.

Request Mapping
In Spring Boot, @RequestMapping is a crucial annotation for mapping HTTP
requests to specific handler methods within controllers. It acts as a bridge,
connecting incoming web requests to the appropriate code that should handle
them.

There are also HTTP method specific shortcut variants of @RequestMapping:


● @GetMapping
● @PostMapping
● @PutMapping
● @DeleteMapping
● @PatchMapping

Request Body In Spring Boot, the @RequestBody annotation is


used to bind the body of an HTTP request to a method parameter in a
controller. This allows you to receive data sent in the request body (typically
JSON or XML) and automatically convert it into a Java object.

PathVariable
The @PathVariable annotation is used to retrieve data from the URL path. By

defining placeholders in the request mapping URL, you can bind those

placeholders to method parameters annotated with @PathVariable. This

allows you to access dynamic values from the URL and use them in your
code. For example, you can extract a user ID from a URL like /users/123 and

pass it to a method that retrieves the corresponding user's details.

Request Parameter

The @RequestParam annotation enables you to extract data from the query

parameters in the request URL. Query parameters are key-value pairs

appended to the URL after a question mark (?). With @RequestParam, you

can specify the name of the parameter to retrieve and bind it to a method

parameter. This is useful when you need to pass additional information or

filters to your API endpoints. For instance, you can extract the value of a

name parameter from a URL like /users/search?name=John and use it to

search for users with the given name.

What Are HTTP Methods and Why Are They Important?


HTTP methods, also known as HTTP verbs, are a set of standardized actions that can be
performed on a resource using the Hypertext Transfer Protocol (HTTP). These methods
define the intended operation to be performed on the resource and provide a uniform way of
interacting with web servers. The most commonly used HTTP methods are GET, POST,
PUT, and DELETE, but there are other methods as well, such as PATCH, HEAD, and
OPTIONS.

HTTP methods are important for several reasons:


1. Resource Manipulation: HTTP methods allow clients to perform various
operations on resources, such as retrieving data, submitting data, updating data,
or deleting data. Each method represents a specific action that can be taken on a
resource, enabling a wide range of interactions between clients and servers.
2. Uniform Interface: HTTP methods provide a uniform interface for interacting with
web resources. By adhering to the standard set of methods, clients and servers
can communicate effectively, regardless of the underlying technologies or
platforms being used. This promotes interoperability and simplifies the
development and integration of web applications.
3. Intent and Semantics: Each HTTP method carries a specific intent and semantic
meaning, making it easier for developers to understand the purpose of an API
endpoint by looking at the method used. For example, a GET request is used to
retrieve data, while a POST request is used to submit data for processing or
storage. By selecting the appropriate method, developers can convey the
intended operation more accurately.
4. Idempotence and Safety: HTTP methods have different characteristics regarding
idempotence and safety. Idempotence means that making multiple identical
requests should have the same outcome. Safe methods, such as GET, should not
cause any modifications or side effects on the server. Understanding these
characteristics helps developers design APIs that adhere to the expected
behavior and minimize unintended side effects or data inconsistencies.
5. RESTful Architecture: HTTP methods play a fundamental role in building RESTful
APIs (Representational State Transfer). REST is an architectural style that
leverages HTTP methods to provide a scalable and flexible approach to designing
web services. Each resource in a RESTful API is typically associated with a
specific URL, and the appropriate HTTP method is used to interact with that
resource.

By understanding and utilizing the appropriate HTTP methods, developers can build robust
and well-designed APIs that adhere to the principles of HTTP and REST. This ensures
consistency, interoperability, and efficiency in the communication between clients and
servers.

Below we will elaborate more on the most commonly used HTTP methods.

GET Method:
The GET method is one of the fundamental HTTP methods used for retrieving data from a
server. It is designed to be safe, meaning it should not modify any data on the server. When
using the GET method, the client requests a representation of a resource from the server.

Here are some key points to consider when working with the GET method in API
development:

1. Retrieving Data: The primary purpose of the GET method is to retrieve data from
the server. It is commonly used to fetch resources such as user profiles, product
information, blog articles, and more. The client sends a GET request to a specific
URL, and the server responds with the requested data.
2. Request Parameters: GET requests can include parameters in the URL to provide
additional information to the server. These parameters are appended to the URL
as query parameters, typically in the form of key-value pairs. For example, a GET
request to retrieve user information for a specific ID could look like: GET /users?
id=123. The server can use these parameters to filter or modify the returned data

accordingly.
3. Idempotence: The GET method is considered idempotent, meaning that multiple
identical GET requests should have the same outcome. It implies that making
multiple GET requests for the same resource should not result in any unintended
side effects or modifications on the server. It allows caching mechanisms to be
employed for efficient retrieval and reduces the risk of unintentional changes or
inconsistencies.
4. Response Codes: The server responds to a GET request with an appropriate
HTTP response code to indicate the success or failure of the request. The most
common response code is 200 (OK), indicating that the request was successful,
and the requested resource is returned in the response body. Other possible
response codes include 404 (Not Found) if the requested resource does not exist,
or 500 (Internal Server Error) if there was an error on the server while processing
the request.
5. Limitations: While the GET method is crucial for retrieving data, it has certain
limitations to consider:
● Data Length: GET requests have limitations on the length of the URL.
Excessive data in the URL can result in truncation, errors, or security
vulnerabilities. It is recommended to keep the data size within
reasonable limits and consider alternative methods (e.g., POST) for
large payloads.
● Security Considerations: Since GET requests expose the data in the
URL, it is important to avoid including sensitive information like
passwords or authentication tokens in the query parameters. Instead,
consider using other secure methods such as headers or request bodies
for transmitting sensitive data.

POST Method:
The POST method is one of the HTTP methods used for submitting data to be processed
by the server. Unlike the GET method, which is used for retrieving data, the POST method
is intended for data submission and can cause modifications on the server. Here are some
important points to consider when working with the POST method:

1. Submitting Data: The primary purpose of the POST method is to submit data to
the server for processing or storage. This data can be in various formats such as
form data, JSON, XML, or binary data. The POST request typically includes a
request body that contains the data being sent to the server.
2. Idempotence: Unlike the GET method, the POST method is generally considered
non-idempotent. This means that multiple identical POST requests may have
different outcomes or effects on the server. For example, submitting the same
POST request multiple times may result in the creation of multiple resources or
duplicate entries.
3. Request Headers: POST requests often include specific headers to provide
additional information about the request or the format of the data being sent. For
example, the “Content-Type” header specifies the format of the data in the
request body, such as “application/json” or “application/x-www-form-urlencoded”.
4. Response Codes: Similar to other HTTP methods, the server responds to a
POST request with an appropriate HTTP response code to indicate the success
or failure of the request. The common response code for a successful POST
request is 201 (Created), indicating that the resource has been successfully
created on the server. Other possible response codes include 200 (OK) for
general success or 400 (Bad Request) for invalid or malformed requests.
5. Limitations: While the POST method is commonly used for data submission, it
also has some limitations to consider:
● Lack of Idempotence: As mentioned earlier, the non-idempotent nature
of the POST method means that repeated identical requests may lead to
unintended side effects. It is important to design APIs in a way that
handles duplicate submissions appropriately and ensures data integrity.
● Lack of Caching: By default, POST requests are typically not cacheable.
Caching is important for improving performance and reducing the load
on the server. If caching is required for POST requests, additional
measures such as Cache-Control headers or server-side caching
strategies need to be implemented.
When using the POST method, it is crucial to ensure proper authentication, authorization,
and input validation to prevent security vulnerabilities and protect the integrity of the server
and data.

Remember to use the appropriate HTTP method based on the intended operation. While
the GET method is used for retrieving data, the POST method is suitable for submitting data
for processing or creating new resources on the server.

PUT Method:
The PUT method is an HTTP method used for updating or replacing a resource on the
server. It is idempotent, meaning that multiple identical PUT requests should have the same
outcome. Here are some important points to consider when working with the PUT method:

1. Updating Resources: The primary purpose of the PUT method is to update an


existing resource on the server. It replaces the entire resource with the new
representation provided in the request. The PUT request typically includes a
request body containing the updated data for the resource.
2. Idempotence: As mentioned earlier, the PUT method is idempotent. It means that
making multiple identical PUT requests should have the same outcome. This
property allows for safe retries of failed requests without causing unintended side
effects or data inconsistencies.
3. Resource Identification: To update a specific resource, the client must provide the
unique identifier or URL of the resource in the PUT request. The server uses this
information to locate the resource and perform the update operation. It is crucial
to ensure the accuracy and integrity of the resource identification mechanism to
prevent unintended modifications to unrelated resources.
4. Partial Updates: By default, the PUT method replaces the entire resource with the
new representation provided in the request body. However, in some cases, it may
be desirable to perform partial updates, modifying only specific fields or properties
of the resource. While the HTTP specification does not directly support partial
updates with the PUT method, some APIs implement custom conventions or use
additional operations (e.g., PATCH) to achieve partial updates.
5. Response Codes: Similar to other HTTP methods, the server responds to a PUT
request with an appropriate HTTP response code to indicate the success or
failure of the request. The common response code for a successful PUT request
is 200 (OK), indicating that the resource has been successfully updated.
Alternatively, if the resource does not exist and a new resource is created, the
response code may be 201 (Created).
6. Limitations: While the PUT method is commonly used for resource updates, it
also has some limitations to consider:
● Lack of Partial Updates: As mentioned earlier, the PUT method typically
replaces the entire resource rather than allowing partial updates to
specific fields. If partial updates are required, alternative approaches like
PATCH or custom conventions can be considered.
● Security Considerations: It is essential to implement proper
authentication, authorization, and validation mechanisms to ensure that
only authorized clients can update the resources. Additionally, input
validation should be performed to prevent invalid or malicious data from
being stored.

When using the PUT method, it is important to handle concurrency and data consistency
issues appropriately. For example, you may use optimistic locking mechanisms or
versioning to ensure that updates do not conflict with other concurrent modifications to the
resource.

Remember to use the appropriate HTTP method based on the intended operation. While
the GET method is used for retrieving data and the POST method is used for submitting
data, the PUT method is suitable for updating existing resources on the server.
DELETE Method:
The DELETE method is an HTTP method used for deleting a specified resource on the
server. It is used to remove a resource permanently from the server. Here are some
important points to consider when working with the DELETE method:

1. Deleting Resources: The primary purpose of the DELETE method is to delete a


specific resource on the server. The client sends a DELETE request to the server,
specifying the URL or identifier of the resource to be deleted.
2. Idempotence: Similar to the PUT method, the DELETE method is also
idempotent. Multiple identical DELETE requests should have the same outcome.
Making repeated DELETE requests for the same resource should not result in
any unintended side effects or modifications on the server.
3. Resource Identification: To delete a specific resource, the client must provide the
unique identifier or URL of the resource in the DELETE request. The server uses
this information to locate and remove the corresponding resource. It is crucial to
ensure the accuracy and integrity of the resource identification mechanism to
prevent accidental deletions of unrelated resources.
4. Response Codes: The server responds to a DELETE request with an appropriate
HTTP response code to indicate the success or failure of the request. The
common response code for a successful DELETE request is 204 (No Content),
indicating that the resource has been successfully deleted. Alternatively, if the
resource does not exist, the response code may be 404 (Not Found).
5. Limitations: While the DELETE method is commonly used for resource deletion, it
is important to consider the following limitations:
● Lack of Safety: Unlike the GET method, which is considered safe and
should not modify any data on the server, the DELETE method performs
irreversible actions. Once a resource is deleted, it cannot be easily
recovered. Therefore, it is crucial to implement appropriate authorization
and authentication mechanisms to ensure that only authorized clients
can initiate DELETE requests.
● Cascading Deletions: In some cases, deleting a resource may have
cascading effects on related resources. For example, deleting a user
may require deleting associated records such as posts or comments. It
is essential to define the behavior and potential cascading actions in
your API’s design and documentation.

Remember to use the appropriate HTTP method based on the intended operation. While
the GET method is used for retrieving data, the POST method is used for submitting data,
the PUT method is used for updating data, the DELETE method is specifically designed for
resource deletion.

You might also like