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

Spring Framework and REST API

The document provides an overview of Client-Server programming and the Spring Framework, highlighting their roles in web applications and REST APIs. It explains key concepts such as Dependency Injection, Inversion of Control, and the architecture of Spring Boot, emphasizing its advantages like reduced configuration and modular design. Additionally, it outlines the structure of REST APIs, including HTTP methods and request handling in a Spring Boot application.
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 views18 pages

Spring Framework and REST API

The document provides an overview of Client-Server programming and the Spring Framework, highlighting their roles in web applications and REST APIs. It explains key concepts such as Dependency Injection, Inversion of Control, and the architecture of Spring Boot, emphasizing its advantages like reduced configuration and modular design. Additionally, it outlines the structure of REST APIs, including HTTP methods and request handling in a Spring Boot application.
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

Spring Framework and REST API

Client–Server Programming

Definition

Client–Server programming is a computing model in which:

 Client sends a request


 Server processes the request
 Server returns response

It is the fundamental architecture used in web applications, mobile apps, and


distributed systems.

Basic Architecture

Real Life Example

Example: Online Shopping (Amazon)

Step-by-step process:

1. User opens Amazon website


2. Browser sends request to Amazon server
3. Server searches product database
4. Server sends product list back to browser

User → Browser → Internet → Server → Database



Response

Java Concept (Simple Illustration)

Although client-server is usually built with frameworks, the concept is:

Client → HTTP Request


Server → Controller processes request
Server → Sends Response

Example response in Spring Boot:

@RestController
public class HelloController {

@GetMapping("/hello")
public String sayHello(){
return "Hello Student!";
}

When user opens:

[Link]

Server responds:

Hello Student!

Spring Framework

Definition

Spring Framework is an open-source Java framework used to build:

 Enterprise applications
 Web applications
 REST APIs
 Microservices

It provides infrastructure support so developers can focus on business logic


instead of configuration.

Why Spring Was Introduced?

Earlier Java Enterprise applications used EJB (Enterprise Java Beans) which
were:

 Complex
 Heavy
 Hard to maintain

Spring solved these problems by introducing:

 Lightweight container
 Dependency Injection
 Easy configuration

Core Idea of Spring

Spring manages objects automatically.

Developer focuses on:

Business Logic

Spring handles:

Object creation
Dependency management
Configuration
Lifecycle management

Spring Architecture
Why We Use Spring Framework?

Key Advantages

Loose Coupling

Classes are not tightly dependent.

Example:

Without Spring:

Car → Engine

With Spring:

Car ← Spring → Engine

Spring injects dependencies.

Easy Testing

Spring applications are easier to test using:

 JUnit
 Mockito
Modular Architecture

Spring has multiple modules:

Spring Core
Spring MVC
Spring Security
Spring Boot
Spring Data

Spring Boot's modern architecture simplifies Java application


development through layered design and auto-configuration,
enabling rapid creation of production-ready apps. It follows a
typical three-tier structure with core Spring Framework
features like dependency injection.

Core Layers

The presentation layer uses controllers to handle HTTP requests


via Spring MVC's DispatcherServlet.
The service layer manages business logic, often using
annotations like @Service for components.
Repositories in the data access layer interact with databases
via Spring Data JPA or similar.
This diagram shows the request flow from client to database
and back, highlighting controller-service-repository interactions.
Key Components

Spring Boot relies on an embedded server like Tomcat for


standalone deployment.
Auto-configuration detects dependencies (via starters) and sets
up beans automatically based on classpath.
The IoC container (ApplicationContext) handles bean lifecycle
and dependency injection across layers.

Request Flow

A client sends an HTTP request, which the DispatcherServlet


routes to a matching @RestController method.
The controller delegates to services, which query repositories
extending JpaRepository for CRUD operations.
Responses return as JSON, with actuators providing monitoring
endpoints for production use.
Faster Development

Spring Boot reduces configuration.

Example:

Earlier Java Web App required:

XML
Servlet Configuration
Server Setup

Spring Boot:

Just run main() method

Dependency Injection (DI)

Definition

Dependency Injection means:

Objects are created and injected automatically by the Spring container.

Instead of creating objects manually.

Without Dependency Injection

class Car {

Engine engine = new Engine();

Problem:

Car is tightly coupled with Engine

With Dependency Injection


class Car {

Engine engine;

Car(Engine engine){
[Link] = engine;
}

Spring will inject Engine automatically.

DI Flow Diagram

Spring Container
Real Life Example

Restaurant Example

Without DI:

Customer hires:

 Cook
 Waiter
 Cleaner

With DI:

Restaurant manager assigns staff automatically.

Manager = Spring Framework.

Inversion of Control (IoC)

Definition

Inversion of Control means:

Control of object creation is transferred from developer to Spring container.


Traditional Programming

Developer creates objects


Developer manages lifecycle

Spring Programming

Spring creates objects


Spring manages lifecycle

IoC Container

Spring container responsible for:

 Creating objects
 Injecting dependencies
 Managing lifecycle

IoC Flow

Application Start
|
v
Spring Container Initialized
|
v
Beans Created
|
v
Dependencies Injected
|
v
Application Ready

Auto Wiring

Definition
Autowiring allows Spring to automatically connect dependencies.

Types of Autowiring

1. By Type
2. By Name
3. Constructor Autowiring

Example

@Component
class Engine {

@Component
class Car {

@Autowired
Engine engine;

Spring automatically connects:

Car → Engine

Real Life Example

Bluetooth device auto connects to phone.

You don't manually connect each time.

AOP (Aspect Oriented Programming)

Definition

AOP separates cross-cutting concerns from business logic.


Examples of cross-cutting concerns:

 Logging
 Security
 Transactions
 Monitoring

Example

Bank Transfer System:

Main logic:

Transfer Money

Additional tasks:

Check security
Log transaction
Check balance

AOP handles these additional tasks.

AOP Structure

Main Business Logic


|
|
+---+---+
| |
Logging Security

Bean Lifecycle

A Bean is simply a Java object managed by Spring.

Bean Lifecycle Steps


1 Application starts
2 Spring container loads configuration
3 Bean created
4 Dependencies injected
5 Bean initialized
6 Bean used
7 Bean destroyed

Bean Lifecycle Diagram

Bean Creation
|
Dependency Injection
|
Initialization
|
Application Use
|
Destruction

Bean Scope

Defines how many objects will be created.

Scope Description
Singleton One object for entire application
Prototype New object every request

REST API

Definition

REST API is a web service architecture used for communication between


systems using HTTP.

REST = Representational State Transfer.

REST Architecture
Client (Browser / App)
|
| HTTP Request
v
REST API
|
v
Database

Real Life Example

Food Delivery App

App → Request restaurant list


Server → Returns restaurant data

HTTP Methods (CRUD)

Method Purpose
GET Retrieve data
POST Insert data
PUT Update data
DELETE Delete data

Example

Student Management API

GET /students
POST /students
PUT /students
DELETE /students

II-Spring Boot

Spring Boot simplifies Spring development.

Advantages:
✔ No XML configuration
✔ Embedded server (Tomcat)
✔ Auto configuration

Spring Boot Architecture

User Request
|
v
Controller Layer
|
v
Service Layer
|
v
Repository Layer
|
v
Database

Build Systems

Maven

Most common build tool.

Handles:

 Dependencies
 Build process
 Packaging

Maven Example

[Link]
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Spring Boot Project Structure

src
└── main
├── java
│ ├── controller
│ ├── service
│ ├── repository

└── resources
└── [Link]

REST Controller

Controller handles incoming HTTP requests.

Example Controller

@RestController
@RequestMapping("/students")
public class StudentController {

@GetMapping
public String getStudents(){
return "All Students";
}

Request Mapping

Maps URL to Java method.

@RequestMapping("/students")

Example:

[Link]
Path Variable

Used when value comes from URL.

Example URL:

/students/10

Code:

@GetMapping("/students/{id}")
public String getStudent(@PathVariable int id){
return "Student id = " + id;
}

Request Parameter

Used in query parameters.

Example URL:

/search?name=Rahul

Code:

@GetMapping("/search")
public String search(@RequestParam String name){
return name;
}

Request Body

Used to send JSON data.

Example:

{
"name":"Rahul",
"age":20
}
Code:

@PostMapping("/students")
public String save(@RequestBody Student student){
return "Student saved";
}

Complete Flow of REST API

User
|
Browser / Mobile App
|
HTTP Request
|
Spring Boot Controller
|
Service Layer
|
Database
|
Response Sent Back
|
User Receives Data

You might also like