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

Java Full Stack Spring Boot

The document provides an overview of Java Full Stack Backend Development, focusing on key components such as Spring Boot, REST APIs, MVC architecture, MySQL integration, CRUD operations, and API testing. It details the workflow of backend processes, the advantages of using Spring Boot, and the role of various annotations in simplifying configuration and enhancing readability. Additionally, it outlines the complete request processing flow, demonstrating how client requests are handled through controllers, services, and repositories to interact with a MySQL database.

Uploaded by

ssravani5566
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 views46 pages

Java Full Stack Spring Boot

The document provides an overview of Java Full Stack Backend Development, focusing on key components such as Spring Boot, REST APIs, MVC architecture, MySQL integration, CRUD operations, and API testing. It details the workflow of backend processes, the advantages of using Spring Boot, and the role of various annotations in simplifying configuration and enhancing readability. Additionally, it outlines the complete request processing flow, demonstrating how client requests are handled through controllers, services, and repositories to interact with a MySQL database.

Uploaded by

ssravani5566
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

Java Full Stack – Backend Development

Backend development is the server-side part of a web application. It is


responsible for processing user requests, executing business logic,
communicating with the database, and sending responses back to the
client (web browser or mobile application).

Backend Workflow

Client (Browser/Postman)


Controller


Service


Repository


MySQL Database


Repository


Service


Controller


JSON Response

1. Spring Boot

Definition

Spring Boot is a Java framework used to build production-ready


applications quickly. It eliminates most configuration work and provides
embedded servers like Tomcat.

Instead of writing many configuration files, Spring Boot automatically


configures the application.
Why do we use Spring Boot?

 Faster application development

 Embedded Tomcat Server

 Auto Configuration

 Easy dependency management

 REST API development

 Microservices development

Features

 Auto Configuration

 Starter Dependencies

 Embedded Server

 Spring MVC

 Spring Data JPA

 Spring Security

 REST Support

Spring Boot Architecture

Client

HTTP Request

Spring Boot Application

Controller

Service

Repository

Database
Advantages

 Less code

 Faster development

 Easy deployment

 Production-ready

 Supports Maven and Gradle

2. REST APIs

Definition

REST (Representational State Transfer) is a web service architecture used


to exchange data between client and server using HTTP methods.

The data is usually transferred in JSON format.

Why REST API?

Without REST API:

Frontend

Cannot directly access database

With REST API:

Frontend

HTTP Request

REST API

Database

HTTP Methods

GET

Retrieve data.

Example

GET /students
Output

[
{
"id":1,
"name":"Rahul"
}
]

POST

Insert new data.

POST /students

Body

{
"name":"Rahul"
}

PUT

Update existing data.

PUT /students/1

DELETE

Delete data.

DELETE /students/1

REST API Flow

Client

HTTP Request

Controller

Service

Repository

Database

JSON Response

Advantages

 Platform independent

 Lightweight

 Uses JSON

 Easy integration

 Faster communication

3. MVC Architecture

MVC stands for

 Model

 View

 Controller

It is a software design pattern used to separate the application into


different layers.

MVC Components

Model
Represents application data.

Example

Student

id
name
department
age

View

The user interface.

Examples

 HTML

 JSP

 React

 Angular

Controller

Receives user requests and returns responses.

Example

@GetMapping("/students")

MVC Flow

User

View


Controller

Service

Repository

Database

Controller

View

Why MVC?

 Separation of concerns

 Easier maintenance

 Code reusability

 Better testing

 Scalability

4. MySQL Database Integration

Definition

MySQL is a relational database used to store application data


permanently.

Spring Boot connects to MySQL using Spring Data JPA and JDBC.
Connection Flow

Application

Spring Boot

JPA

MySQL Database

Database Operations

 Insert

 Select

 Update

 Delete

Sample Table

I Nam Departme
D e nt

1 Rahul CSE

2 Priya ECE

Advantages

 Open Source

 Fast

 Reliable

 Secure

 Supports SQL
5. CRUD Operations

CRUD stands for

 Create

 Read

 Update

 Delete

These are the four basic operations performed on database records.

Create

Adds new data.

POST /students

Database

Rahul

Read

Retrieves data.

GET /students

Update

Modifies existing data.

PUT /students/1

Delete

Removes data.

DELETE /students/1

CRUD Flow
User

Controller

Service

Repository

Database

Response

6. API Testing

Definition

API testing verifies that REST APIs work correctly by sending requests and
checking responses.

Common tools:

 Postman

 Swagger UI

 Thunder Client

 Insomnia

Why API Testing?

 Check API functionality

 Validate JSON responses

 Test HTTP status codes


 Verify database operations

 Detect errors early

Example API Testing

GET

GET localhost:8080/students

Response

[
{
"id":1,
"name":"Rahul"
}
]

POST

Request

POST localhost:8080/students

Body

{
"name":"Rahul",
"department":"CSE"
}

Response

Student Added Successfully

Common HTTP Status Codes

Cod
Meaning
e

200 OK

201 Created

400 Bad Request

401 Unauthorized
Cod
Meaning
e

404 Not Found

Internal Server
500
Error

Complete Backend Request Flow

User


Browser/Postman

HTTP Request


Controller

Business Logic

Service

Database Operations

Repository (Spring Data JPA)

SQL Queries

MySQL Database

Data Retrieved

Repository


Service

JSON Object

Controller

HTTP Response

Client (Browser/Postman)

Tech Stack Used

Technology Purpose

Java Programming Language

Spring Boot Backend Framework

Spring MVC Request handling and MVC architecture

Spring Data
Database access using repositories
JPA

MySQL Relational Database

REST API Communication between frontend and backend

Postman API testing

Maven Dependency and project management

ORM framework for mapping Java objects to


Hibernate
database tables

Spring Boot Annotations – Complete Explanation

What is an Annotation?

An annotation in Java is a special marker (starts with @) that provides


instructions or metadata to the Java compiler or the Spring Framework.

In Spring Boot, annotations tell Spring what a class or method should


do, so you don't have to write a lot of configuration code.

Syntax

@AnnotationName
Example:

@RestController
public class StudentController {

Here, @RestController tells Spring Boot that this class handles HTTP
requests and returns data in JSON format.

Why Do We Use Annotations?

Without annotations, developers need to write a lot of XML configuration


files.

With annotations:

 Less code

 Easy to understand

 Automatic configuration

 Better readability

 Faster development

How Do Annotations Work?

Step-by-Step Process

When the application starts:

Application Starts


Spring Boot scans all packages


Finds Annotations (@Controller, @Service...)


Creates Objects (Beans)


Stores them in Spring Container


Application is Ready

This process is called Component Scanning.

What is Spring Container?

The Spring Container is the core of the Spring Framework.

Its job is to:

 Create objects

 Manage objects

 Inject dependencies

 Destroy objects when the application stops

Spring Container

------------------------
StudentController Object
StudentService Object
StudentRepository Object
------------------------

Instead of creating objects manually, Spring creates them automatically.

Common Spring Boot Annotations

1. @SpringBootApplication

Definition

This is the main annotation used to start a Spring Boot application.

@SpringBootApplication
public class StudentApplication {

public static void main(String[] args) {


[Link]([Link],args);
}
}

Work

It combines three annotations:


@SpringBootConfiguration

@EnableAutoConfiguration

@ComponentScan

Process

Application Starts

@SpringBootApplication

Scans all packages

Creates required objects

Starts Tomcat Server

Application Ready

2. @Component

Definition

Marks a Java class as a Spring-managed component (bean).

@Component
public class Student {

Work

Spring creates the object automatically.

Without Spring
Student s = new Student();

With Spring

@Component
public class Student {

Spring creates the object.

3. @Controller

Definition

Used to create a web controller.

@Controller
public class HomeController {

Work

Handles requests and returns HTML or JSP pages.

Flow

Browser

@Controller

HTML Page

4. @RestController

Definition

Used for REST APIs.

@RestController
public class StudentController {

}
Work

Returns JSON data instead of HTML.

Example

@GetMapping("/student")
public Student getStudent(){

Output

{
"id":1,
"name":"Rahul"
}

Difference

@Controller

Returns

[Link]
[Link]

@RestController

Returns

{
"name":"Rahul"
}

5. @Service

Definition

Represents the business logic layer.

@Service
public class StudentService{

Work

Contains calculations, validations and business rules.


Example

public Student saveStudent(Student s){

return [Link](s);

Flow

Controller

@Service

Repository

6. @Repository

Definition

Represents the database layer.

@Repository
public class StudentRepository{

Work

Performs CRUD operations.

Insert

Update

Delete

Retrieve

Flow
Service

Repository

MySQL

7. @Autowired

Definition

Automatically injects one object into another.

Without Autowired

StudentService service=new StudentService();

With Autowired

@Autowired
StudentService service;

Spring creates the object.

Process

Controller

@Autowired

Service Object Created

Ready to Use

8. @RequestMapping

Definition
Maps URL requests.

@RequestMapping("/student")

Example

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

Now every API starts with

/student

Example

/student/all

/student/add

/student/delete

9. @GetMapping

Definition

Handles GET request.

@GetMapping("/all")

Work

Retrieve data.

Flow

Browser

GET Request

@GetMapping


Controller

JSON Response

10. @PostMapping

Definition

Handles POST request.

@PostMapping("/save")

Work

Insert new data.

Flow

User

POST

Controller

Service

Database

11. @PutMapping

Definition

Update existing record.

@PutMapping("/update/{id}")
Work

Modify existing data.

12. @DeleteMapping

Definition

Delete data.

@DeleteMapping("/delete/{id}")

Work

Removes record.

13. @PathVariable

Definition

Reads values from URL.

Example

[Link]

@GetMapping("/{id}")

public Student getStudent(@PathVariable int id){

Spring automatically stores

id=5

14. @RequestParam

Definition

Reads query parameters.

Example URL

[Link]

@GetMapping("/student")

public Student getStudent(@RequestParam String name){


}

Output

Rahul

15. @RequestBody

Definition

Converts JSON into a Java Object.

Client sends

{
"name":"Rahul",
"department":"CSE"
}

Controller

@PostMapping

public Student save(@RequestBody Student student){

Spring automatically converts JSON to a Student object.

16. @Entity

Definition

Maps a Java class to a database table.

@Entity
public class Student{

Database

Student Table

17. @Table

Specifies the table name.


@Entity

@Table(name="students")

18. @Id

Defines the Primary Key.

@Id

private int id;

19. @GeneratedValue

Automatically generates the primary key.

@Id

@GeneratedValue(strategy=[Link])

private int id;

20. @Column

Maps a field to a database column.

@Column(name="student_name")

private String name;

Complete Request Processing Flow Using Annotations

Suppose the client sends a request to save a student.

Client (Browser/Postman)


POST /students


@PostMapping


@RestController


@RequestBody
(JSON → Student Object)


@Service
(Business Logic)


@Repository


@Entity
(Student → Database Table)


MySQL Database


Student Saved


Repository


Service


Controller


JSON Response Returned

Summary Table

Annotation Used On Purpose

@SpringBootApplicat
Main Class Starts the Spring Boot application
ion

@Component Class Creates a Spring-managed bean


Annotation Used On Purpose

Handles web page requests


@Controller Class
(HTML/JSP)

Handles REST API requests and


@RestController Class
returns JSON/XML

@Service Class Contains business logic

@Repository Class Performs database operations

Field/
@Autowired Injects dependencies automatically
Constructor

@RequestMapping Class/Method Maps a base URL or request path

@GetMapping Method Handles HTTP GET requests

@PostMapping Method Handles HTTP POST requests

@PutMapping Method Handles HTTP PUT requests

@DeleteMapping Method Handles HTTP DELETE requests

Handles partial updates with HTTP


@PatchMapping Method
PATCH

Method
@PathVariable Reads values from the URL path
Parameter

Method Reads query parameters from the


@RequestParam
Parameter URL

Method Converts request JSON into a Java


@RequestBody
Parameter object

@Entity Class Maps a class to a database table

@Table Class Specifies the database table name

@Id Field Marks the primary key

Automatically generates primary


@GeneratedValue Field
key values

@Column Field Maps a field to a database column


Spring Boot Architecture – Controller, Service, Repository &
Database (Complete Process)

Understanding the Spring Boot Architecture is essential because


almost every Spring Boot application follows this layered design.

The architecture consists of four main layers:

Client (Browser / Postman)




Controller Layer


Service Layer


Repository Layer


MySQL Database

Each layer has a specific responsibility and communicates only with the
next layer.

Real-Time Example

Let's consider a Student Management System.

Suppose a user wants to add a new student.

The student details are:

ID : 101
Name : Rahul
Department : CSE

The user clicks Save.

Now let's see what happens internally.

Step 1: Client Sends Request

The request comes from:

 Browser

 Mobile App
 React

 Angular

 Postman

Example Request

POST [Link]

JSON Data

{
"name":"Rahul",
"department":"CSE"
}

This request reaches the Controller.

Step 2: Controller Layer

Annotation Used

@RestController
@RequestMapping("/students")

What is Controller?

The Controller is the entry point of the application.

It receives every HTTP request from the client.

Think of it as a Receptionist in a hospital.

A receptionist:

 Receives the patient.

 Collects information.

 Sends the patient to the doctor.

Similarly, the Controller:

 Receives requests.

 Reads request data.

 Sends it to the Service layer.

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

@Autowired
StudentService service;

@PostMapping
public Student saveStudent(@RequestBody Student student){
return [Link](student);
}

Annotation Explanation

@RestController

Tells Spring Boot:

"This class handles REST API requests."

Without this annotation, Spring won't know this class should receive HTTP
requests.

@RequestMapping("/students")

Sets the base URL.

[Link]

Instead of writing /students for every method, we define it once.

@PostMapping

Handles POST requests.

POST /students

@RequestBody

Converts JSON into a Java object.

Client sends
{
"name":"Rahul",
"department":"CSE"
}

Spring automatically converts it to

Student student

@Autowired

Automatically injects the StudentService object.

Instead of

StudentService service = new StudentService();

Spring creates it automatically.

Controller Process

Client

POST Request

@RestController

@RequestBody
(JSON → Object)

Student Object

Calls Service Layer

Step 3: Service Layer

Annotation

@Service

What is Service?

The Service layer contains the business logic.

Think of it as the Doctor.

A doctor:
 Checks reports.

 Decides treatment.

 Gives medicine.

Similarly, Service:

 Validates data.

 Performs calculations.

 Applies business rules.

 Calls Repository.

Example

@Service
public class StudentService {

@Autowired
StudentRepository repository;

public Student saveStudent(Student student){

return [Link](student);

Annotation Explanation

@Service

Marks this class as the Business Logic Layer.

Spring automatically creates the object.

@Autowired

Injects Repository.

Instead of

StudentRepository repository = new StudentRepository();


Spring creates it.

Service Process

Controller

Service

Validate Student

Business Logic

Repository

Example Business Logic

Suppose

Age <18

Don't allow admission.

if([Link]()<18){

throw new Exception("Admission Not Allowed");

This logic belongs in the Service layer—not in the Controller.

Step 4: Repository Layer

Annotation

@Repository
What is Repository?

Repository communicates with the database.

Think of it as a Cashier.

Doctor writes medicine.

Cashier updates the records.

Similarly,

Service tells Repository

Save student.

Repository executes SQL.

Example

@Repository
public interface StudentRepository
extends JpaRepository<Student,Integer>{

Notice that we don't write SQL manually for common operations because
JpaRepository provides methods like save(), findAll(), findById(), and
deleteById().

Annotation Explanation

@Repository

Marks this interface/class as the Database Layer.

Spring automatically recognizes it and enables database access.

Repository Process

Service

Repository


JPA

Hibernate

SQL Query

Database

Step 5: Entity

Annotation

@Entity
@Table(name="students")

What is Entity?

Entity maps the Java class to the database table.

Example

@Entity
@Table(name="students")
public class Student{

@Id
@GeneratedValue(strategy=[Link])
private int id;

private String name;

private String department;

Annotation Work
@Entity

Maps Java class → Database Table

Student Class

Student Table

@Table

Specifies the table name.

students

@Id

Primary Key

id

@GeneratedValue

Automatically increments ID.

Step 6: Database

Database stores the data permanently.

Example Table
Nam Departme
ID
e nt

10
Rahul CSE
1

The Repository sends SQL (through JPA/Hibernate) to MySQL, and MySQL


stores the record.

Complete Request Flow

USER


Browser / Postman


HTTP Request


@RestController

@PostMapping()

@RequestBody
(JSON → Student Object)


StudentController


@Service

Business Logic


@Repository

[Link]()


Hibernate (ORM)

Generates SQL


MySQL Database

Student Record Saved


Success Response


StudentController


JSON Response to Client

Why Do We Separate These Layers?

Layer Responsibility Why It Is Needed

Controller Receives HTTP requests Keeps request handling


(@RestController) and sends responses separate from business logic

Contains business rules Makes the application easier


Service (@Service)
and validations to maintain and test

Repository Performs database Separates persistence logic


(@Repository) operations from business logic

Allows JPA/Hibernate to
Maps Java objects to
Entity (@Entity) convert objects into database
database tables
records

Stores application data Provides reliable and


Database (MySQL)
permanently persistent storage

Dependency Injection (DI) in Spring Boot


Dependency Injection (DI) is one of the core concepts of the Spring
Framework. It is a design pattern where the Spring Container creates
and manages objects (beans) and automatically provides them to
other classes when needed.

Instead of a class creating its own objects, Spring injects the required
objects automatically.

What is Dependency?

A dependency is an object that another class needs to perform its work.

Example

Suppose you have:

 StudentController

 StudentService

The StudentController needs the StudentService to process requests.

Here, StudentService is the dependency of StudentController.

StudentController


StudentService

What is Dependency Injection?

Dependency Injection means Spring automatically provides the


required object (dependency) to another class.

Instead of writing:

StudentService service = new StudentService();

Spring injects it automatically.

Without Dependency Injection

public class StudentController {

StudentService service = new StudentService();

public void saveStudent() {


[Link]();
}
}

Problems

 Tight coupling

 Difficult to test

 Hard to maintain

 Manual object creation

With Dependency Injection

@RestController
public class StudentController {

@Autowired
private StudentService service;

public void saveStudent() {


[Link]();
}
}

Now Spring creates the StudentService object and injects it into


StudentController.

How Dependency Injection Works

Application Starts


Spring Container Starts


Scans @Service

Creates StudentService Object


Scans @RestController

Finds @Autowired

Injects StudentService into StudentController


Application Ready

Real-Time Example

Imagine a Restaurant.

 Customer → Client

 Waiter → Controller

 Chef → Service

 Kitchen → Repository

 Store Room → Database

The waiter does not cook the food. He simply passes the order to the
chef.

Similarly, the Controller does not create the Service object. Spring
provides it automatically.

Customer


Waiter (Controller)


Chef (Service)


Kitchen (Repository)


Store Room (Database)

Types of Dependency Injection in Spring

1. Constructor Injection (Recommended)

Spring injects dependencies through the class constructor.


@Service
public class StudentService {
}

@RestController
public class StudentController {

private final StudentService service;

public StudentController(StudentService service) {


[Link] = service;
}
}

Advantages

 Recommended by Spring

 Easy to test

 Supports immutable (final) fields

 Dependencies are mandatory

2. Setter Injection

Spring injects dependencies using a setter method.

@RestController
public class StudentController {

private StudentService service;

@Autowired
public void setStudentService(StudentService service) {
[Link] = service;
}
}

Advantages

 Dependency can be changed later

 Useful for optional dependencies

3. Field Injection
Spring injects directly into the field.

@RestController
public class StudentController {

@Autowired
private StudentService service;
}

Advantages

 Less code

 Easy to write

Disadvantages

 Harder to unit test

 Not recommended for large applications

Which Injection Should You Use?

Injection Type Recommended Why?

Constructor Best practice, easier to test,


✅ Yes
Injection supports immutable fields

Setter Injection ✅ Sometimes Good for optional dependencies

⚠️Learning/Small Simple, but not recommended for


Field Injection
Projects production code

Role of @Autowired

@Autowired tells Spring:

"Find the required bean from the Spring Container and inject it here."

Example:

@Service
public class StudentService {
}

@RestController
public class StudentController {
@Autowired
private StudentService service;
}

Spring creates the StudentService bean and injects it into


StudentController.

Complete Flow of Dependency Injection

Application Starts


@SpringBootApplication


Component Scan


Creates StudentService Bean (@Service)


Creates StudentController Bean (@RestController)


Finds @Autowired


Injects StudentService into StudentController


Client Sends Request


Controller Calls Service


Service Calls Repository


Repository Accesses Database


Response Returned to Client
Spring Boot Architecture with Dependency Injection

Client


@RestController
(StudentController)

│ @Autowired

@Service
(StudentService)

│ @Autowired

@Repository
(StudentRepository)


MySQL Database

Advantages of Dependency Injection

 Reduces tight coupling between classes.

 Improves code reusability.

 Makes applications easier to test.

 Improves maintainability.

 Spring automatically manages object creation and lifecycle.

 Encourages clean architecture and Separation of Concerns


(SoC).

Interview Questions

1. What is Dependency Injection?

Dependency Injection is a design pattern in which Spring creates and


injects required objects (dependencies) into other classes instead of the
classes creating them manually.

2. What is a dependency?
A dependency is an object that another class needs to perform its work.

3. Which dependency injection type is recommended in Spring


Boot?

Constructor Injection is the recommended approach because it is more


testable, supports immutable fields, and makes dependencies explicit.

4. What is the purpose of @Autowired?

@Autowired tells Spring to automatically inject the required bean from the
Spring Container into a class.

You might also like