Unit 5 Spring Boot WT
Unit 5 Spring Boot WT
(“Imagine you want to build a small house (a computer program). Normally, you’d have to
figure out where to get bricks, wood, nails, tools, and spend a lot of time putting everything
together from scratch.
Spring Boot is like a house kit that gives you almost everything ready — the walls, roof, and
tools — so you can quickly build your house without worrying about the tiny details.
In computer terms:
So, Spring Boot saves time and makes building apps easier, especially if you want to get things
working quickly”)
It is built on top of the Spring Framework and simplifies the process of developing Java web
applications by:
1. @SpringBootApplication
This is called an annotation — it’s like a special label or tag you put on your code.
It tells Spring Boot: “Hey, this is the main class for the application. Please set up
everything automatically for me!”
It combines three important annotations:
o @Configuration (marks the class as a source of bean definitions)
o @EnableAutoConfiguration (tells Spring Boot to guess and configure things
automatically)
o @ComponentScan (tells Spring where to look for other parts of your app)
This is the main method — the entry point of any Java program.
When you run your app, the computer starts executing code from here.
String[] args means it can accept some extra information if you want to pass any
when starting.
4. [Link]([Link], args);
This is the most common way. It’s a simple text file where you write key-value pairs.
Example:
[Link]=8081
[Link]=jdbc:mysql://localhost:3306/mydb
[Link]=root
[Link]=secret
[Link]=DEBUG
[Link]=8081 means your app will run on port 8081 instead of the default 8080.
[Link].* are for connecting to a database.
[Link] controls the amount of log info you get.
You can also use YAML format, which looks cleaner for big configs.
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: secret
You can use @Value annotation to get config values directly in your code.
@Value("${[Link]}")
private int port;
@Component
@ConfigurationProperties(prefix = "[Link]")
public class DataSourceConfig {
private String url;
private String username;
private String password;
src/main/resources/
It lets you change how your app behaves without changing your code. For example, you can:
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
[Link]([Link], args);
}
}
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
EXPLANATION:
1. @SpringBootApplication :
This tells Spring Boot: "This is the main class for the app."
It combines three things:
o @Configuration: This class can have setup/configuration.
o @EnableAutoConfiguration: Spring Boot will automatically set up things for
you based on what’s in your project.
o @ComponentScan: Spring will look for other classes to use (like controllers or
services) in this package.
This is the main method, the starting point when you run your Java
program.
4. [Link]([Link], args);
It creates the application context, sets up everything, and runs your app.
5. @RestController
It means all methods inside this class will send data (like JSON or text) back in the
HTTP response.
7. @GetMapping("/hello")
This means: When someone visits the URL /hello using an HTTP GET request,
run the method right below this annotation.
Defines a method named hello that will be called when /hello is visited.
Because of @RestController, this text will be sent directly to the browser or client as
the response.
In summary:
They reduce a lot of manual setup. Spring Boot figures out what to do based on these labels, so
you write less code and get things done faster!
Spring Boot Actuator is a tool that helps you monitor and manage your Spring Boot
application while it is running.
It gives you ready-made endpoints (special URLs) to see information about your app's health,
metrics, configuration, and more — without you having to write all that monitoring code
yourself.
Why use Spring Boot Actuator?
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
implementation '[Link]:spring-boot-starter-actuator'
To expose all actuator endpoints over HTTP, add this to your [Link]:
[Link]=*
[Link]=health,info,metrics
{
"status": "UP"
}
{
"status": "DOWN",
"details": {
"db": {
"status": "DOWN",
"error": "Cannot connect to database"
}
}
}
You can add your own health checks by implementing the HealthIndicator interface.
@Component
public class MyHealthCheck implements HealthIndicator {
@Override
public Health health() {
// Check your app's custom status
boolean everythingIsOk = checkSomething();
if (everythingIsOk) {
return [Link]().withDetail("CustomCheck", "All
good!").build();
} else {
return [Link]().withDetail("CustomCheck", "Problem
found!").build();
}
}
Since Actuator endpoints can expose sensitive info, it’s a good idea to protect them.
You can add Spring Security and restrict access only to authorized users.
Summary
What Actuator Does Why It’s Useful
Shows app health Know if your app and its parts are OK
Lets you change logging levels Adjust logging without restarting app
Provides debugging info (threads, HTTP requests) Helps troubleshoot issues faster
Spring Boot Actuator is a powerful submodule of Spring Boot that helps you monitor and
manage your Spring Boot application in production. It provides a set of built-in endpoints that
expose operational information about the application—such as health, metrics, environment
properties, and more—through HTTP or JMX.
(Think of your Spring Boot application like a car. It runs, does its job, and takes you places
(like processing data or serving a website).
👉 You need a dashboard or indicator lights — that’s exactly what Spring Boot Actuator
gives you.)
Spring Boot Actuator adds special URLs (called endpoints) to your app.
You can open these in a browser or tool like Postman and see helpful info.
Endpoint Description
/actuator/health Health info (DB, disk space, services)
/actuator/info Static application info (from [Link])
/actuator/metrics Application metrics (memory, GC, request count)
/actuator/env Environment properties (props, env vars, etc.)
/actuator/beans Lists all Spring beans with dependencies
/actuator/configprops Shows configuration properties and values
/actuator/mappings Request-to-handler method mappings
/actuator/loggers Runtime log levels per package/class
/actuator/threaddump JVM thread dump
/actuator/httptrace Last 100 HTTP requests (if enabled)
/actuator/auditevents Audit events in the system
Example:
[Link]
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
In [Link]:
[Link]=*
[Link]
Is It Safe?
In Spring Boot, build systems are tools that help manage dependencies, compile source code,
package applications, and automate development tasks
(Example 1: A build system helps you build, package, and manage your Spring Boot project.
Think of it like a kitchen that takes raw ingredients (your code) and prepares a finished meal (a
working app).
A build system does all of this for your Spring Boot project:
1. ✅ Maven
Maven is the most popular build tool for Java and Spring Boot projects.
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
✅Maven Pros:
2. ✅ Gradle
Add dependencies
Build settings
How to run the app
group = '[Link]'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
dependencies {
implementation '[Link]:spring-boot-starter-web'
}
This does the same job as Maven but in a simpler, more flexible format.
Build and Run Commands:
gradle build # Builds the project
gradle bootRun # Runs the app
Gradle Pros:
Spring Boot supports two main build systems: Maven and Gradle
Both do the same job: add dependencies, build, and run your app
When you create a Spring Boot application, it gives you a standard folder and file structure to
keep everything organized.
my-springboot-app/
├── src/
│ └── main/
│ ├── java/
│ │ └── com/
│ │ └── example/
│ │ └── myapp/
│ │ ├── [Link] <-- Main class
│ │ ├── controller/ <-- Web layer (APIs)
│ │ ├── service/ <-- Business logic
│ │ └── model/ <-- Data classes
│ └── resources/
│ ├── [Link] <-- App settings
│ ├── static/ <-- HTML, CSS, JS
│ └── templates/ <-- Thymeleaf views
├── test/ <-- Unit tests
├── [Link] or [Link] <-- Build file
1. [Link]
@SpringBootApplication
public class MyAppApplication {
public static void main(String[] args) {
[Link]([Link], args);
}
}
2. controller/ folder
Contains controller classes that handle HTTP requests (like GET, POST).
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}
3. service/ folder
This is where you write business logic — the core functionality of your app.
@Service
public class UserService {
public String getUserName() {
return "John Doe";
}
}
4. model/ folder
5. resources/[Link]
Example:
[Link]=8081
[Link]=jdbc:mysql://localhost:3306/mydb
6. resources/static/
[Link]
Images
JavaScript
CSS
7. resources/templates/
Example:
templates/
└── [Link]
8. test/ folder
Example:
@SpringBootTest
class MyAppApplicationTests {
@Test
void contextLoads() {
}
}
9. [Link] or [Link]
Summary
Folder/File Purpose
Folder/File Purpose
In a Spring Boot application, you usually start your app using the main() method.
But what if you want to run some code automatically when the app starts?
For example:
CommandLineRunner Runs code after the app starts, and gets command-line arguments
Runner Type Description
ApplicationRunner Also runs code after the app starts, but gets more structured input
Use this if you want to run some logic right after the app starts.
Example:
import [Link];
import [Link];
@Component
public class MyStartupRunner implements CommandLineRunner {
@Override
public void run(String... args) {
[Link]("App has started! Running some startup logic...");
}
}
📄 What’s happening:
Example:
import [Link];
import [Link];
import [Link];
@Component
public class MyAppRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) {
[Link]("Running with arguments: " +
[Link]());
}
}
What’s happening:
Runners are used to run code automatically after your Spring Boot app starts
Two main types:
o CommandLineRunner – simple
o ApplicationRunner – more advanced
You just need to implement one of these interfaces and use @Component
What is a LOGGER?
A logger is like a notebook your app uses to write down messages while it runs.
These messages help you:
Spring Boot uses SLF4J (Simple Logging Facade for Java) with Logback as the default logging
framework.
Example:
import [Link];
import [Link];
import [Link];
@Service
public class MyService {
Logging Levels:
Configure in [Link]:
[Link]=INFO
[Link]=DEBUG
[Link]=[Link]
Building RESTful Web Services in Spring Boot (in Simple Language)
A REST API (or RESTful web service) lets two applications talk over the internet using
HTTP (like browsers and websites).
For example:
A mobile app asks your Spring Boot app: “Give me all users.”
Your app replies with user data in JSON format.
Use [Link]
Add:
Spring Web
Spring Boot DevTools (optional)
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping
public List<User> getAllUsers() {
return users;
}
@PostMapping
public String createUser(@RequestBody User user) {
[Link](user);
return "User added!";
}
@PutMapping("/{id}")
public String updateUser(@PathVariable Long id, @RequestBody User
newUser) {
for (User user : users) {
if ([Link]().equals(id)) {
[Link]([Link]());
[Link]([Link]());
return "User updated!";
}
}
return "User not found!";
}
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Long id) {
[Link](u -> [Link]().equals(id));
return "User deleted!";
}
}
Postman (GUI)
curl (command line)
Swagger (if you add it)
Summary
Logger:
REST CONTROLLER:
A Rest Controller is a special Spring Boot class that handles HTTP requests (like GET,
POST, PUT, DELETE) and returns data (usually JSON) to whoever called it.
import [Link];
import [Link];
@RestController
@RequestMapping("/api/users") // Base URL for all methods in this controller
public class UserController {
// GET /api/users
@GetMapping
public List<String> getAllUsers() {
return users;
}
// POST /api/users
@PostMapping
public String addUser(@RequestBody String user) {
[Link](user);
return "User added!";
}
// DELETE /api/users/{index}
@DeleteMapping("/{index}")
public String deleteUser(@PathVariable int index) {
if (index >= 0 && index < [Link]()) {
[Link](index);
return "User removed!";
}
return "Invalid index!";
}
}
Explanation:
1. Imports
import [Link].*;
import [Link];
import [Link];
2. Class Declaration
@RestController
@RequestMapping("/api/users") // Base URL for all methods in this controller
public class UserController {
@RestController tells Spring this class handles REST API requests and will return
JSON responses (not HTML).
@RequestMapping("/api/users") means all URLs inside this class will start with
/api/users.
So, if you have a method with @GetMapping, its full URL becomes /api/users.
3. Data Storage
private List<String> users = new ArrayList<>();
@GetMapping means this method will respond to HTTP GET requests at /api/users.
When a client (like Postman or a browser) calls GET /api/users, this method returns the
full list of users.
Spring automatically converts the List<String> to JSON so the client gets something
like:
@RestController automatically converts your Java objects into JSON (or XML) to
send as a response.
@Controller is used mostly when you want to return HTML views (web pages).
Summary:
It helps your app know what to do when someone visits a certain page or sends data
@RequestMapping is used in controller classes to define how HTTP requests should be handled.
For example:
@RestController
@RequestMapping("/api")
public class HelloController {
@RequestMapping("/hello")
public String sayHello() {
return "Hello from Spring Boot!";
}
}
Spring Boot uses Spring MVC under the hood. When a request hits the application, Spring
looks at the controller classes and their mapping annotations (like @RequestMapping) to figure
out which method to invoke.
🔍 Examples
Spring Boot encourages using more readable shorthand annotations introduced in Spring 4+:
Annotation Equivalent
Annotation Equivalent
@GetMapping("/users")
public List<User> getAllUsers() {
return [Link]();
}
REQUEST BODY:
What is @RequestBody in Spring Boot?
@RequestBody is used when your app needs to receive data from the user (client) in the body
of the request, usually in JSON format.
You're building an app that takes a form where someone sends their name and age.
But instead of filling a form on a website, they send the info using an HTTP POST request like
this:
{
"name": "Ali",
"age": 25
}
Spring Boot can take this data and automatically put it into a Java object using @RequestBody.
🔍 Real Example:
@PostMapping("/person")
public String receivePerson(@RequestBody Person person) {
return "Hello " + [Link]() + ", you are " + [Link]() +
" years old.";
}
}
🔍 How It Works:
[Link]
{
"name": "Ali",
"age": 25
}
PATH VARIABLE:
In Spring Boot, @PathVariable is used to extract values from the URI path and bind them to method
parameters in controller methods. It’s commonly used in RESTful web services where resources are
accessed via dynamic paths.
In Spring Boot, the term PATH variable usually refers to the part of a URL that contains
dynamic values. These are used in REST APIs to send information through the URL itself.
💡 Example:
Let's say you build a REST API to get a user by their ID.
@GetMapping("/user/{id}")
public String getUserById(@PathVariable String id) {
return "User ID is: " + id;
}
💡 Quick Comparison:
Request Parameters are key-value pairs sent in the URL (usually in GET requests), after the
question mark ?.
[Link]
👉 Output:
[Link]
@GetMapping("/search")
public String searchItems(@RequestParam String query,
@RequestParam(required = false) String sort) {
return "Searching for: " + query + ", Sorted by: " + (sort != null ? sort
: "default");
}
👉 URL:
[Link]
👉 Output:
🔍 Summary
Term Meaning
👉 URL:
[Link]
👉 Output:
They define the action you want to perform on a resource (like a user, product, or article) in a
REST API.
Method Purpose
@GetMapping("/users/{id}")
public String getUser(@PathVariable String id) {
return "Getting user with ID: " + id;
}
}
GET [Link]
👉 Response:
@PostMapping("/users")
public String createUser(@RequestBody String userData) {
return "Creating user with data: " + userData;
}
}
{
"name": "Alice",
"email": "alice@[Link]"
}
👉 Response:
@PutMapping("/users/{id}")
public String updateUser(@PathVariable String id, @RequestBody String
userData) {
return "Updating user " + id + " with data: " + userData;
}
}
👉 Call with:
PUT [Link]
Request Body:
{
"name": "Alice Updated",
"email": "alice_new@[Link]"
}
👉 Response:
@DeleteMapping("/users/{id}")
public String deleteUser(@PathVariable String id) {
return "Deleting user with ID: " + id;
}
}
👉 Call:
DELETE [Link]
👉 Response:
🔍 Summary Table
HTTP Method Annotation Purpose Requires Body? URL Example
@GetMapping("/{id}")
public String getUser(@PathVariable String id) { return "Getting user " +
id; }
@PostMapping
public String createUser(@RequestBody String data) { return "Creating
user: " + data; }
@PutMapping("/{id}")
public String updateUser(@PathVariable String id, @RequestBody String
data) {
return "Updating user " + id + ": " + data;
}
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable String id) {
return "Deleting user " + id;
}
}
BUILDING WEB APPLICATIONS in Spring Boot is one of its core strengths. Let me walk
you through how to build a web application using Spring Boot, in a simple and clear way —
from setup to working endpoints.
3. Step-by-Step Guide
Use [Link]
Choose:
Project: Maven
Dependencies:
o Spring Web
o Thymeleaf (optional, for HTML views)
o Spring Boot DevTools (for auto-restart)
Step 2: Main Application Class
@SpringBootApplication
public class WebAppApplication {
public static void main(String[] args) {
[Link]([Link], args);
}
}
@GetMapping
public List<User> getUsers() {
return users;
}
@PostMapping
public String addUser(@RequestBody User user) {
[Link](user);
return "User added successfully!";
}
}
In resources/templates/[Link]:
<!DOCTYPE html>
<html xmlns:th="[Link]
<head><title>Home</title></head>
<body>
<h1>Welcome to Spring Boot Web App</h1>
</body>
</html>
And create a controller:
@Controller
public class PageController {
@GetMapping("/")
public String homePage() {
return "home"; // maps to [Link]
}
}
mvn spring-boot:run
Or:
Now open:
🔍 Summary
Part What It Does