0% found this document useful (0 votes)
5 views17 pages

Java & Spring Boot Guide: Classes & Patterns

This guide covers Java fundamentals and Spring Boot patterns essential for building applications. It includes practical examples like a chatbot, e-commerce app, and todo list app, alongside a quick reference for common issues and solutions. Key concepts include classes, constructors, DTOs, controllers, and the request/response flow in Spring Boot.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views17 pages

Java & Spring Boot Guide: Classes & Patterns

This guide covers Java fundamentals and Spring Boot patterns essential for building applications. It includes practical examples like a chatbot, e-commerce app, and todo list app, alongside a quick reference for common issues and solutions. Key concepts include classes, constructors, DTOs, controllers, and the request/response flow in Spring Boot.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java & Spring Boot Essentials

The Complete Reference Guide

Classes • Constructors • Getters/Setters • Spring Boot Patterns

A practical guide for building any Spring Boot application


■ Table of Contents
Part 1: Java Fundamentals
• What is a Class?
• Fields (Variables in Classes)
• Constructors
• Getters and Setters
• The 'this' Keyword
• Access Modifiers

Part 2: Spring Boot Patterns


• Controllers
• DTOs (Data Transfer Objects)
• Request/Response Flow
• Common Annotations

Part 3: Practical Examples


• Your RAG Chatbot
• E-commerce App
• Todo List App

Part 4: Quick Reference


• When to Use What
• Common Patterns
• Troubleshooting
PART 1: Java Fundamentals

■ What is a Class?
A class is a blueprint for creating objects. Think of it like a cookie cutter - the class is the cutter, objects are the
cookies.

Real-world analogy:
• Class = Car blueprint (defines what a car has: color, model, speed)
• Object = Actual car (your red Toyota with specific speed)

Basic class structure:


public class User { // Fields (data the class holds) private String username;
private String email; // Constructor (how to create objects) public User() { } //
Methods (what the class can do) public void login() { [Link]("User
logged in"); } }

Creating objects from the class:


User user1 = new User(); // Create first user User user2 = new User(); // Create
second user // Each object is independent!
■ Fields (Variables in Classes)
Fields are variables that belong to a class. They store the data/state of each object.

Why make fields private?


• Encapsulation: Hide internal data from outside access
• Control: You decide how data is accessed/modified (via getters/setters)
• Validation: Can check data before setting it

public class Product { // WRONG - anyone can access/modify directly public String
name; public double price; // RIGHT - controlled access private String name; private
double price; // Access through methods (getters/setters) public double getPrice() {
return price; } public void setPrice(double price) { if (price < 0) { throw new
Exception("Price can't be negative!"); } [Link] = price; // Validation before
setting! } }
■■ Constructors
Constructors are special methods that run when you create an object. They initialize the object's data.

Types of Constructors:

Type When to Use Example

No-args When creating empty objects User user = new User();


Constructor that you'll set values later [Link]("admin");

Parameterized When you know all values User user = new User(
Constructor upfront "admin",
"admin@[Link]"
);

Both! Give flexibility - Provide both constructors


use whichever fits in the same class

Complete Example:
public class LoginRequest { private String username; private String password; //
No-args constructor (Spring Boot needs this!) public LoginRequest() { } //
Parameterized constructor (convenient for testing) public LoginRequest(String
username, String password) { [Link] = username; [Link] = password; }
// Getters and setters below... }
// Usage: LoginRequest req1 = new LoginRequest(); // Empty object
[Link]("admin"); // Set later LoginRequest req2 = new
LoginRequest("admin", "pass123"); // All at once
■ Getters and Setters
Getters and setters are methods that control access to private fields.

The Pattern (You'll Use This 1000 Times):


private String fieldName; // Getter - READ the value public String getFieldName() {
return fieldName; } // Setter - WRITE the value public void setFieldName(String
fieldName) { [Link] = fieldName; }

Naming Convention (CRITICAL!):


Field Name Getter Name Setter Name

username getUsername() setUsername(String)

password getPassword() setPassword(String)

isActive isActive() setActive(boolean)

email getEmail() setEmail(String)

Why Use Getters/Setters Instead of Public Fields?


• Validation: Check values before setting
• Flexibility: Change internal implementation without breaking code
• Debugging: Add logging/breakpoints in setters
• Security: Control what can be read/written
• Spring Boot requires them: For @RequestBody to work!

Example with Validation:


public class User { private String email; private int age; public void
setEmail(String email) { if (![Link]("@")) { throw new
IllegalArgumentException("Invalid email!"); } [Link] = email; // Only set if
valid } public void setAge(int age) { if (age < 0 || age > 150) { throw new
IllegalArgumentException("Invalid age!"); } [Link] = age; } }
■ The 'this' Keyword
this refers to the current object. Use it to distinguish between field names and parameter names.

When to use 'this':


public class User { private String username; // Field // NEED 'this' - parameter
name = field name public void setUsername(String username) { [Link] =
username; // [Link] = the field // username = the parameter } // DON'T NEED
'this' - different names public void setUsername(String name) { username = name; //
Clear which is which } // Constructor - ALWAYS use 'this' public User(String
username, String email) { [Link] = username; [Link] = email; } }
Best Practice: Always use 'this' in setters and constructors for clarity, even when not strictly required.
■ Access Modifiers
Modifier Who Can Access When to Use

public Everyone Classes, methods you want


others to use

private Only this class Fields (almost always)


Helper methods

protected This class + Inheritance


subclasses (advanced)

(default) Same package Rarely used


intentionally

Standard Pattern for Spring Boot:


public class MyClass { // public - others can use private String field1; // private
- hide internal data private int field2; public MyClass() { } // public - others can
create public String getField1() { // public - controlled access return field1; }
public void setField1(String field1) { this.field1 = field1; } }
PART 2: Spring Boot Patterns

■ Controllers
Controllers handle HTTP requests. They're the entry point for your API.

The Standard Controller Pattern:


@RestController // ← Makes this a REST API @RequestMapping("/api/resource") // ←
Base URL for all endpoints public class ResourceController { @GetMapping // ← GET
/api/resource public List<Resource> getAll() { // Return all resources }
@GetMapping("/{id}") // ← GET /api/resource/123 public Resource
getById(@PathVariable Long id) { // Return one resource } @PostMapping // ← POST
/api/resource public Resource create(@RequestBody ResourceRequest req) { // Create
new resource } @PutMapping("/{id}") // ← PUT /api/resource/123 public Resource
update(@PathVariable Long id, @RequestBody ResourceRequest req) { // Update resource
} @DeleteMapping("/{id}") // ← DELETE /api/resource/123 public void
delete(@PathVariable Long id) { // Delete resource } }
■ DTOs (Data Transfer Objects)
DTOs are simple classes that carry data between client and server. They're just fields + getters/setters.

The Standard DTO Pattern:


public class LoginRequest { private String username; private String password; //
No-args constructor (REQUIRED for Spring Boot!) public LoginRequest() { } //
Parameterized constructor (optional, for convenience) public LoginRequest(String
username, String password) { [Link] = username; [Link] = password; }
// Getters public String getUsername() { return username; } public String
getPassword() { return password; } // Setters public void setUsername(String
username) { [Link] = username; } public void setPassword(String password) {
[Link] = password; } }
VS Code Shortcut: Right-click in class → Source Action → Generate Getters and Setters
■ Request/Response Flow
Understanding how data flows from client to server and back:

Step What Happens Code

1. Client Postman/React sends {


sends request JSON to server "username": "admin",
"password": "pass"
}

2. Spring Boot @RequestBody converts LoginRequest req


receives JSON to Java object (has username + password)

3. Controller Your code runs, String user = [Link]();


processes uses getters to if ([Link]("admin")) {...}
access data

4. Controller Return String, return "Login successful!";


returns object, or DTO

5. Spring Boot Converts to JSON, {


sends response sends to client "message": "Login successful!"
}
■ Common Spring Boot Annotations
Annotation Where Purpose Example

@RestController Class Make class handle @RestController


REST requests public class MyController

@RequestMapping Class/Method Define base URL path @RequestMapping("/api/users")

@GetMapping Method Handle GET requests @GetMapping


public List getAll()

@PostMapping Method Handle POST requests @PostMapping


public void create()

@PutMapping Method Handle PUT requests @PutMapping("/{id}")


public void update()

@DeleteMapping Method Handle DELETE @DeleteMapping("/{id}")


requests public void delete()

@RequestBody Parameter Get JSON from create(@RequestBody User u)


request body

@RequestParam Parameter Get URL/form search(@RequestParam String q)


parameters

@PathVariable Parameter Get value from URL getById(@PathVariable Long id)


PART 3: Practical Examples

■ Example 1: Your RAG Chatbot

[Link] (DTO):
public class LoginRequest { private String username; private String password; public
LoginRequest() { } public String getUsername() { return username; } public void
setUsername(String username) { [Link] = username; } public String getPassword() {
return password; } public void setPassword(String password) { [Link] = password; } }

[Link]:
@RestController @RequestMapping("/api/auth") public class LoginController {
@PostMapping("/login") public String login(@RequestBody LoginRequest request) { String user =
[Link](); String pass = [Link](); if ([Link]("admin") &&
[Link]("password123")) { return "Login successful!"; } return "Invalid credentials"; } }

[Link] (DTO):
public class ChatRequest { private String message; public ChatRequest() { } public String
getMessage() { return message; } public void setMessage(String message) { [Link] =
message; } }

[Link]:
@RestController @RequestMapping("/api/chat") public class ChatController { @PostMapping public
String chat(@RequestBody ChatRequest request) { String userMessage = [Link](); //
Process with RAG/Spring AI String aiResponse = processWithRAG(userMessage); return aiResponse;
} }
■ Example 2: E-commerce App

[Link] (DTO):
public class Product { private Long id; private String name; private double price; private int
stock; public Product() { } public Product(Long id, String name, double price, int stock) {
[Link] = id; [Link] = name; [Link] = price; [Link] = stock; } // Getters and
setters for all fields public Long getId() { return id; } public void setId(Long id) { [Link]
= id; } // ... etc }

[Link]:
@RestController @RequestMapping("/api/products") public class ProductController { @GetMapping
public List<Product> getAllProducts() { // Return all products } @GetMapping("/{id}") public
Product getProductById(@PathVariable Long id) { // Return one product } @PostMapping public
Product createProduct(@RequestBody Product product) { // Save new product }
@PutMapping("/{id}") public Product updateProduct(@PathVariable Long id, @RequestBody Product
product) { // Update product } }
■ Example 3: Todo List App

[Link] (DTO):
public class Todo { private Long id; private String title; private boolean completed; public
Todo() { } public Long getId() { return id; } public void setId(Long id) { [Link] = id; }
public String getTitle() { return title; } public void setTitle(String title) { [Link] =
title; } public boolean isCompleted() { return completed; } public void setCompleted(boolean
completed) { [Link] = completed; } }

[Link]:
@RestController @RequestMapping("/api/todos") public class TodoController { private List<Todo>
todos = new ArrayList<>(); @GetMapping public List<Todo> getAll() { return todos; }
@PostMapping public Todo create(@RequestBody Todo todo) { [Link]((long) ([Link]() +
1)); [Link](todo); return todo; } @DeleteMapping("/{id}") public void delete(@PathVariable
Long id) { [Link](t -> [Link]().equals(id)); } }
PART 4: Quick Reference

■ When to Use What?


Need Use Example
Hold data for DTO class with LoginRequest,
request/response fields + getters/setters ChatRequest

Handle HTTP Controller with LoginController,


requests @RestController ChatController

Get JSON from @RequestBody @PostMapping


request body annotation create(@RequestBody User u)

Get URL parameter @RequestParam search(@RequestParam String q)

Get value from URL @PathVariable getById(@PathVariable Long id)

Create object Parameterized new User("admin", "pass")


with all values constructor

Create empty object, No-args constructor User u = new User();


set later [Link]("admin");

■ Copy-Paste Templates

Template 1: Simple DTO


public class MyRequest { private String field1; private String field2; public MyRequest() { }
public String getField1() { return field1; } public void setField1(String field1) {
this.field1 = field1; } public String getField2() { return field2; } public void
setField2(String field2) { this.field2 = field2; } }

Template 2: Simple Controller


@RestController @RequestMapping("/api/resource") public class ResourceController {
@PostMapping public String create(@RequestBody MyRequest request) { // Your logic here return
"Success!"; } }
■ Common Issues & Solutions
Problem Cause Solution
Red underline on Missing import Ctrl+. → Import
@RestController

"No default Missing no-args Add: public MyClass() { }


constructor" constructor

Fields always null No getters/setters Add getters and setters


in controller

Can't access Trying to access Use getter:


private field directly [Link]()

"[Link]" Typo or field Check spelling,


causes error doesn't exist ensure field declared

■ Final Tips
• Always make fields private - Use getters/setters for access
• Always add a no-args constructor - Spring Boot needs it!
• Follow naming conventions - getUsername(), setUsername()
• Use 'this' in setters and constructors - Clearer code
• Let VS Code generate code - Right-click → Source Action → Generate Getters/Setters
• One DTO per request/response type - LoginRequest, LoginResponse, ChatRequest, etc.
• Controllers handle requests, DTOs hold data - Keep them separate
• Test with Postman after each new endpoint - Catch errors early

■ You're Ready to Build!


With these fundamentals, you can build any Spring Boot application. Remember: practice makes perfect. Each
class you write, each controller you create, makes the next one easier!

You might also like