0% found this document useful (0 votes)
9 views26 pages

SpringBoot Notes

The document provides comprehensive study notes on Spring Boot, covering its setup, project structure, REST API concepts, and dependency injection. It outlines key topics including the advantages of Spring Boot over the traditional Spring Framework, how to create REST APIs, and the use of annotations for managing application components. Additionally, it explains the importance of the Spring Container and dependency injection for effective application development.
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)
9 views26 pages

SpringBoot Notes

The document provides comprehensive study notes on Spring Boot, covering its setup, project structure, REST API concepts, and dependency injection. It outlines key topics including the advantages of Spring Boot over the traditional Spring Framework, how to create REST APIs, and the use of annotations for managing application components. Additionally, it explains the importance of the Spring Container and dependency injection for effective application development.
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 Boot

Complete Study Notes

From Basics to 3-Layer Architecture

Topics Covered
Step Topic
Step 1 What is Spring Boot & Project Setup
Step 2 Project Structure & Key Files
Step 3 REST API & HTTP Concepts
Step 4 Annotations & Dependency Injection
Step 5 3-Layer Architecture with Code

Prerequisites: Basic Java Knowledge


Step 1: What is Spring Boot & Project Setup

1.1 What is Spring Boot?


Spring Boot is a framework built on top of the Spring Framework that makes it easy to create
stand-alone, production-ready Java applications with minimal configuration.

Key Principle

"Convention over Configuration"


Spring Boot makes smart default choices so you don't have to configure everything manually.
You focus on writing business logic — Spring Boot handles the plumbing.

Spring Framework vs Spring Boot


Spring Framework Spring Boot
Powerful but requires lots of manual setup Auto-configures everything for you
XML configuration files needed Zero XML — uses annotations and properties
You install & configure Tomcat separately Tomcat is embedded inside your app
Like a car kit — assemble yourself Like a car ready to drive out of the box

1.2 What Can You Build?


Type Example
REST APIs Backend for a mobile/web app
Web Applications Full server-rendered websites
Microservices Small independent services
Database-connected apps CRUD applications

1.3 How Spring Boot Works — The Big Picture


Your Java Code
|
v
Spring Boot Application
|
v
Embedded Tomcat Server <-- No external server installation needed!
|
v
Runs on port 8080
|
v
Browser / Client accesses: [Link]

Embedded Server: Traditional Java web apps needed an external server (Apache Tomcat)
installed separately. Spring Boot bundles Tomcat inside your app. Just run a .jar file and your
server is live.

1.4 Spring Initializr — Project Setup


Go to [Link] — this is the official tool that generates a ready-to-use Spring Boot
project.

Every Setting Explained


Setting Your Choice Why
Project Maven Build tool — manages dependencies via [Link].
More common in enterprises.
Language Java You already know Java!
Spring Boot Version Latest stable (no SNAPSHOT = unstable/in-development. Avoid those.
SNAPSHOT)
Packaging Jar Self-contained. Run anywhere with: java -jar
[Link]
Java Version 17 or 21 LTS versions — stable and widely supported

Project Metadata Fields


Group: [Link] <- Reverse domain name. Identifies your
organisation.
Artifact: springdemo <- Your project/app name.
Name: springdemo <- Display name (auto-filled from Artifact).
Description: My first app <- Just a description.
Package name: [Link] <- Auto-generated. This is the root package
of all your Java files.
Dependencies to Add
Dependency What It Does
Spring Web Lets you build REST APIs. Includes embedded
Tomcat. This is the core dependency.
Spring Boot DevTools Auto-restarts the app when you change code.
Like live-reload for Java.

Maven vs Gradle — Build Tools Compared


Maven Gradle
Uses [Link] (XML format) Uses [Link] (Groovy/Kotlin)
More common in enterprises More modern, faster builds
Easier for beginners More flexible but has steeper learning curve

1.5 What is a Starter?


Instead of adding 10 separate libraries, Spring Boot bundles them into one starter:

spring-boot-starter-web includes:
- Spring MVC (web framework)
- Embedded Tomcat (server)
- Jackson (JSON conversion)
- Validation libraries

All added with just ONE dependency in [Link]!


Step 2: Project Structure & Key Files

2.1 The Full Project Structure


springdemo/
|
+-- src/
| +-- main/
| | +-- java/
| | | +-- com/learn/springdemo/
| | | +-- [Link] <-- Entry point of your app
| | |
| | +-- resources/
| | +-- static/ <-- CSS, JS, images
| | +-- templates/ <-- HTML templates
| | +-- [Link] <-- App configuration file
| |
| +-- test/
| +-- java/
| +-- [Link] <-- Test file
|
+-- [Link] <-- Maven config (MOST
important)
+-- mvnw / [Link] <-- Maven wrapper scripts

2.2 [Link] — The Entry Point


package [Link];

import [Link];
import [Link];

@SpringBootApplication // Magic annotation — explained below


public class SpringdemoApplication {

public static void main(String[] args) {


[Link]([Link], args);
} // ^^ Starts everything: Tomcat, configs, scanning
}

@SpringBootApplication — What It Really Does


This single annotation secretly combines THREE annotations:
@SpringBootApplication
|
+-- @SpringBootConfiguration
| Marks this as a configuration class
|
+-- @EnableAutoConfiguration
| Tells Spring Boot to AUTO-CONFIGURE everything
| (sets up Tomcat, JSON parsing etc. automatically)
|
+-- @ComponentScan
Tells Spring to SCAN this package and sub-packages
for your classes (Controllers, Services, etc.)

What is Auto-Configuration?

When Spring Boot sees 'Spring Web' in your dependencies, it automatically:


- Starts an embedded Tomcat server
- Sets it to port 8080
- Sets up JSON support
All without you writing a single config line!

2.3 [Link] — The Project Blueprint


[Link] stands for Project Object Model. It is Maven's instruction file for your entire project.

<!-- Project Identity -->


<groupId>[Link]</groupId>
<artifactId>springdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>

<!-- Spring Boot Parent - your project inherits default settings from here -->
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.0</version>
</parent>

<!-- Dependencies -->


<dependencies>
<!-- Starter for REST APIs + embedded Tomcat -->
<dependency>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- Auto-restart on code change -->


<dependency>
<artifactId>spring-boot-starter-devtools</artifactId>
</dependency>
</dependencies>

Term in [Link] Meaning Java Analogy


<parent> Your project inherits defaults from Like extending a base class
Spring Boot's parent POM
<dependencies> Libraries your project needs. Maven Like import statements
downloads them.
starter-web Bundle of libraries for web development Like a library package
scope: test Only used during testing, not in final app Like test-only imports

2.4 [Link] — Configuration File


Currently empty, but this is where you configure your entire app. No need to rewrite Java code just
to change settings.

# Change the port your app runs on (default is 8080)


[Link]=8080

# Name of your application


[Link]=springdemo

# Database connection (you will add this in Step 6)


[Link]=jdbc:mysql://localhost:3306/mydb
[Link]=root
[Link]=secret

2.5 Other Files


File / Folder Purpose
static/ Place CSS, JavaScript, image files here. Served
directly to browser.
templates/ Place HTML template files here (used with
Thymeleaf templating engine).
mvnw / [Link] Maven Wrapper. Run Maven commands
WITHOUT having Maven installed on your
system.
[Link] Auto-generated test file. Tests that your app starts
without crashing.
2.6 Running Your App
In IntelliJ IDEA:
Click the green Run (play) button next to main() method

In Terminal:
./mvnw spring-boot:run (Mac/Linux)
[Link] spring-boot:run (Windows)

Expected console output:


Started SpringdemoApplication in 2.345 seconds
Tomcat started on port(s): 8080

Open browser: [Link]


You will see 'Whitelabel Error Page' -- this is GOOD!
It means app is running but no endpoints created yet.
Step 3: REST API & HTTP Concepts

3.1 What is a REST API?


REST stands for REpresentational State Transfer. It is a set of rules for how computers
communicate with each other over the internet via HTTP.

CLIENT (Browser / Mobile App / Postman)


|
| HTTP Request: GET /students
v
REST API (Your Spring Boot App)
|
| Processes the request
v
DATABASE or Business Logic
|
v
REST API sends HTTP Response back
|
v
CLIENT receives: [{id:1, name:'Alice'}, {id:2, name:'Bob'}]

3.2 HTTP Methods — The Verbs of REST


Every HTTP request has a method that describes the intention. Always use the right method for the
right action.

Method Purpose Example URL


GET Fetch / Read data GET /students
POST Create new data POST /students
PUT Update existing data PUT /students/1
DELETE Delete data DELETE /students/1

3.3 HTTP Status Codes


When the server responds, it sends a status code telling you what happened:
Status Code Meaning
200 OK Request succeeded. Data returned successfully.
201 Created New resource was created successfully (used
with POST).
400 Bad Request Client sent wrong or malformed data.
404 Not Found The requested resource does not exist.
500 Internal Server Error Something crashed on the server side.

3.4 Your First Controller


package [Link];

import [Link];
import [Link];

@RestController // Marks this class as a REST API handler


public class HelloController {

@GetMapping("/hello") // Maps GET /hello to this method


public String sayHello() {
return "Hello, Spring Boot!"; // Sent as HTTP response body
}
}

@RestController — What It Really Does


@RestController
|
+-- @Controller
| 'This class handles incoming web requests'
|
+-- @ResponseBody
'Return values go DIRECTLY as HTTP response body'
'(not as an HTML web page)'

3.5 Passing Data in URLs — Two Ways


Way 1: @PathVariable — Data Inside the URL Path
@GetMapping("/hello/{name}") // {name} is a placeholder
public String greetUser(@PathVariable String name) {
return "Hello, " + name + "!";
}

// URL: [Link]
// Response: Hello, John!

Way 2: @RequestParam — Data as Query String


@GetMapping("/greet")
public String greetWithParam(@RequestParam String name) {
return "Good morning, " + name + "!";
}

// URL: [Link]
// Response: Good morning, John!

@PathVariable @RequestParam
URL: /users/42 URL: /users?id=42
Use to identify a specific resource Use for filtering, searching, optional inputs
Example: Get user BY id Example: Search users BY name

3.6 Returning JSON Automatically


When you return a Java object, Spring uses Jackson library to automatically convert it to JSON:

// Java Object
@GetMapping("/student")
public Student getStudent() {
return new Student("John", 20);
}

// Automatically sent as JSON:


// {
// "name": "John",
// "age": 20
// }

Jackson — Automatic JSON Conversion

Spring Boot includes Jackson library which automatically:


- Converts Java Object --> JSON (called Serialization)
- Converts JSON --> Java Object (called Deserialization)
You don't write a single line for this. It just works!
Requirement: Your model class MUST have getters for serialization to work.
Step 4: Annotations & Dependency Injection

4.1 What Are Annotations?


An annotation is a label/marker you put on a class or method that gives instructions to the Spring
framework. Spring reads these labels at startup and acts accordingly.

@RestController --> 'Hey Spring, this class handles HTTP requests'


@GetMapping --> 'Hey Spring, call this method for GET /hello'
@Service --> 'Hey Spring, this is a business logic class'
@Autowired --> 'Hey Spring, inject the required dependency here'

4.2 The Spring Container


The Spring Container (also called Application Context) is the brain of your Spring Boot app. It:

• Creates all your objects (Beans)


• Manages their entire lifecycle
• Connects (wires) them together automatically
• Destroys them when the app shuts down

+----------------------------------------------+
| SPRING CONTAINER |
| |
| +---------------+ +-----------------+ |
| | StudentService| |StudentRepository| |
| +---------------+ +-----------------+ |
| |
| +-----------------+ +----------------+ |
| |StudentController| | EmailService | |
| +-----------------+ +----------------+ |
| |
| Spring creates ALL of these and connects |
| them together automatically at startup |
+----------------------------------------------+

4.3 What is a Bean?


A Bean is any object that is created and managed by the Spring Container.
// NOT a Bean -- you created it manually
StudentService service = new StudentService();

// IS a Bean -- Spring creates and manages it


@Service
public class StudentService { }
// The moment you add @Service, Spring takes ownership of this object

4.4 Dependency Injection


Dependency Injection (DI) means: instead of a class CREATING its own dependencies, those
dependencies are PROVIDED (injected) from outside by Spring.

The Problem WITHOUT Dependency Injection


public class OrderController {
// BAD: Manually creating dependency
private OrderService orderService = new OrderService(); // Tightly
coupled!

public void placeOrder() {


[Link]();
}
}

// Problems:
// 1. OrderController is hardcoded to use ONLY this OrderService
// 2. If OrderService constructor changes, update EVERYWHERE
// 3. Cannot swap a fake service for testing
// 4. You manage object creation manually -- messy and error-prone

The Solution WITH Dependency Injection


@Service
public class OrderService {
public void process() {
[Link]("Order processed!");
}
}

@RestController
public class OrderController {

private final OrderService orderService; // Just DECLARE the need

@Autowired // Spring: 'I will provide the OrderService for you'


public OrderController(OrderService orderService) {
[Link] = orderService; // Spring injects it here
}

@GetMapping("/order")
public String placeOrder() {
[Link]();
return "Order placed!";
}
}

What Spring Does Behind the Scenes


App starts
|
v
Spring scans all classes in your package
|
+-- Finds @Service on OrderService --> Creates OrderService Bean
+-- Finds @RestController on Controller --> Creates Controller Bean
|
v
Spring sees @Autowired on Controller constructor
|
v
'Controller needs an OrderService'
|
v
Finds the OrderService Bean already created
|
v
INJECTS it into OrderController automatically
|
v
App is ready! GET /order calls OrderController which uses OrderService

4.5 Three Ways to Inject Dependencies


1. Constructor Injection (RECOMMENDED)
@RestController
public class StudentController {

private final StudentService studentService; // final = cannot be changed


later

@Autowired // Optional in newer Spring versions if only ONE constructor


public StudentController(StudentService studentService) {
[Link] = studentService;
}
}

// Why best:
// - Dependencies clearly visible in constructor
// - 'final' ensures they can't be accidentally changed
// - Easiest to write unit tests

2. Field Injection (Common but not recommended)


@RestController
public class StudentController {

@Autowired
private StudentService studentService; // Spring injects directly into
field
}

// Why not recommended:


// - Cannot use 'final'
// - Hides dependencies (not visible in constructor)
// - Harder to write unit tests

3. Setter Injection (Rare)


@RestController
public class StudentController {

private StudentService studentService;

@Autowired
public void setStudentService(StudentService studentService) {
[Link] = studentService;
}
}
// Used only when the dependency is OPTIONAL

4.6 Stereotype Annotations — Defining Beans by Role


@Component
(Generic Spring-managed Bean)
|
+-------------+-------------+
| | |
@Controller @Service @Repository
(Web Layer) (Business (Database
Logic) Layer)

Annotation Used On Purpose


@Component Any class Generic Bean — no specific role defined
@RestController Web/API classes Handles HTTP requests, returns JSON/text
@Service Business logic Contains your app's processing logic
@Repository Database classes Talks to the database / data source
@Configuration Config classes Defines Beans and app configuration

Important Note

@Service and @Repository are both @Component underneath.


The difference is SEMANTIC -- they tell developers and Spring what role the class plays.
Spring also adds extra features to @Repository (like automatic exception translation for DB
errors).
Step 5: 3-Layer Architecture — Line by Line

5.1 Why 3 Layers?


If you put everything in one class, it becomes impossible to maintain as your app grows.

Layer Responsibility
Controller Layer Handles HTTP requests and sends HTTP
responses ONLY. No logic.
Service Layer Contains all business logic ONLY. No HTTP, no
direct DB access.
Repository Layer Talks to the database ONLY. No HTTP, no
business logic.

HTTP Request --> Controller --> Service --> Repository -->


Database
HTTP Response <-- Controller <-- Service <-- Repository <--
Database

RULE: Each layer only talks to the layer DIRECTLY below it.
Controller --> Service --> Repository (never skip layers)

5.2 Project Structure


src/main/java/com/learn/springdemo/
|
+-- [Link] (entry point)
+-- controller/
| +-- [Link] (Layer 1: handles HTTP)
+-- service/
| +-- [Link] (Layer 2: business logic)
+-- repository/
| +-- [Link] (Layer 3: data access)
+-- model/
+-- [Link] (data object -- no layer)

5.3 Model — [Link]


package [Link];
public class Student {

private int id; // private: can only be accessed via


getters/setters
private String name;
private int age;

public Student() { } // No-arg constructor -- REQUIRED by Jackson


// Jackson calls this first when converting JSON
to object

public Student(int id, String name, int age) { // Parameterized


constructor
[Link] = id; // '[Link]' = class field, 'id' = constructor
param
[Link] = name;
[Link] = age;
}

// Getters -- Jackson uses these to convert Object --> JSON


public int getId() { return id; }
public String getName() { return name; }
public int getAge() { return age; }

// Setters -- Jackson uses these when converting JSON --> Object


public void setId(int id) { [Link] = id; }
public void setName(String name) { [Link] = name; }
public void setAge(int age) { [Link] = age; }
}

Why Getters & Setters Are Critical

Without GETTERS: JSON response will be empty {}


Without SETTERS: JSON body cannot be converted to Student object
Without NO-ARG CONSTRUCTOR: Jackson cannot create Student from JSON -- crash!
These three together are what allow automatic JSON <--> Java Object conversion.

5.4 Repository Layer — [Link]


package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
@Repository // Marks as Bean. Role: data access only.
public class StudentRepository {

// In-memory list acting as our fake database for now


private List<Student> students = new ArrayList<>();

public StudentRepository() { // Constructor runs when Spring creates this


Bean
[Link](new Student(1, "Alice", 20)); // Seed data
[Link](new Student(2, "Bob", 22));
[Link](new Student(3, "Charlie", 21));
}

public List<Student> findAll() {


return students; // Return entire list
}

public Student findById(int id) {


return [Link]() // Convert list to Stream for
processing
.filter(s -> [Link]() == id) // Keep only student with
matching id
.findFirst() // Get first match (returns
Optional)
.orElse(null); // If no match found, return null
}

public void save(Student student) {


[Link](student); // Add new student to our list
}
}

5.5 Service Layer — [Link]


package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@Service // Marks as Bean. Role: business logic only.


public class StudentService {

// Declares a dependency on StudentRepository


private final StudentRepository studentRepository;
// 'final' means once Spring assigns it, it can never be replaced

@Autowired // Spring: inject a StudentRepository Bean into this


constructor
public StudentService(StudentRepository studentRepository) {
[Link] = studentRepository;
}

public List<Student> getAllStudents() {


return [Link]();
// In real apps, add logic here:
// - filter inactive students
// - sort by name
// - check access permissions
}

public Student getStudentById(int id) {


return [Link](id);
}

// Service is responsible for generating the ID -- that is business logic


// Controller should NOT know how IDs are generated
public void addStudent(String name, int age) {
int newId = [Link]().size() + 1; // Generate new ID
Student newStudent = new Student(newId, name, age); // Create Student
[Link](newStudent); // Ask repo to
save
}
}

5.6 Controller Layer — [Link]


package [Link];

import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];

@RestController // Handles HTTP requests, returns JSON


@RequestMapping("/students") // Base URL for ALL methods in this class
public class StudentController {

private final StudentService studentService;

@Autowired
public StudentController(StudentService studentService) {
[Link] = studentService;
}

@GetMapping // GET /students (no extra path needed)


public List<Student> getAllStudents() {
return [Link]();
// Jackson auto-converts List<Student> --> JSON array
}

@GetMapping("/{id}") // GET /students/{id} e.g. GET /students/2


public Student getStudentById(@PathVariable int id) {
return [Link](id);
// Spring auto-converts String '2' from URL to int
}

@PostMapping // POST /students


public String addStudent(@RequestBody Student student) {
// @RequestBody: takes JSON from request body and converts to Student
object
// Jackson uses no-arg constructor + setters for this conversion
[Link]([Link](), [Link]());
return "Student added successfully!";
}
}

5.7 Complete Request Flow Diagram


GET /students/2
|
v
[Link](2) [@RestController]
|
| calls
v
[Link](2) [@Service]
|
| calls
v
[Link](2) [@Repository]
|
| searches in-memory list
v
Returns: Student(2, 'Bob', 22)
|
^ passes back up through each layer
|
StudentController receives Student object
|
v
Jackson converts it to JSON automatically
|
v
HTTP Response: 200 OK
{ 'id': 2, 'name': 'Bob', 'age': 22 }

5.8 Testing Your Endpoints


Endpoint URL Expected Response
GET all students [Link] [{id:1,name:Alice},{id:2,name:Bob}...]
GET by ID [Link] {id:2, name:Bob, age:22}
POST new student POST /students with JSON body Student added successfully!

POST request body (send via Postman):


{
"name": "Diana",
"age": 23
}

Tip: Download Postman (free) from [Link] to send POST requests.


Browsers can only send GET requests natively.

5.9 Key Annotations — Full Quick Reference


Annotation Layer What It Does
@SpringBootApplication Main class Combines @Configuration +
@EnableAutoConfiguration + @ComponentScan
@RestController Controller Marks class as REST API handler. Returns data, not
HTML pages.
@RequestMapping Controller Sets base URL prefix for all endpoints in the class
@GetMapping Controller Maps HTTP GET request to a method
@PostMapping Controller Maps HTTP POST request to a method
@PutMapping Controller Maps HTTP PUT request to a method
@DeleteMapping Controller Maps HTTP DELETE request to a method
@PathVariable Controller Extracts value from URL path: /students/{id}
@RequestParam Controller Extracts query parameter: /students?name=John
@RequestBody Controller Converts JSON request body to Java object
@Service Service Marks class as business logic Bean
@Repository Repository Marks class as data access Bean
@Autowired Any Tells Spring to inject required dependency
@Component Any Generic Spring Bean marker
Quick Reference Cheatsheet

Key Terms Glossary


Term Definition
Spring Boot Framework that auto-configures Spring apps.
Convention over Configuration.
Spring Container The brain. Creates, manages, and connects all
Beans automatically.
Bean Any Java object created and managed by the
Spring Container.
Dependency Injection Spring provides objects their dependencies
instead of them creating their own.
Auto-Configuration Spring Boot automatically sets up Tomcat, JSON
support etc. from dependencies.
Starter A bundle of related libraries e.g. spring-boot-
starter-web includes Tomcat + MVC + Jackson.
Maven Build tool that manages dependencies via
[Link] file.
[Link] Maven configuration file. Defines project identity,
dependencies, build settings.
Jackson Library that automatically converts Java Objects
<--> JSON.
Tomcat The web server. Spring Boot embeds it so no
external installation needed.
REST API Rules for how computers communicate over
HTTP using methods GET/POST/PUT/DELETE.
Serialization Converting Java Object to JSON (for sending in
response).
Deserialization Converting JSON to Java Object (from incoming
request body).

The 3-Layer Rule


Controller --> ONLY handles HTTP (requests & responses)
Service --> ONLY contains business logic
Repository --> ONLY talks to the database
Each layer speaks ONLY to the layer directly below it.
NEVER skip layers. NEVER mix responsibilities.

Common Mistakes to Avoid


Mistake Correct Approach
Putting business logic in Controller Move all logic to Service layer
Calling Repository directly from Controller Always go through Service layer
Forgetting no-arg constructor in Model Jackson needs it to create objects from JSON
Forgetting getters in Model Jackson needs getters to write JSON fields
Using new keyword to create Spring-managed Let Spring inject them with @Autowired
objects
Field injection with @Autowired Use constructor injection for best practice

You might also like