Spring Boot Cheatsheet

A comprehensive Spring Boot cheatsheet to help you master modern Java programming.

1. INTRODUCTION TO SPRING BOOT

1.1 What is Spring Boot?

  • Spring Boot is a tool that helps you create Java applications quickly.
  • Normally, when you use the Spring Framework, you have to do a lot of setup (like writing long configuration files).
  • Spring Boot removes that headache. It gives you ready-to-use settings so you can start building your application faster.

Think of it like this:

  • Spring Framework = raw ingredients, you cook everything yourself.
  • Spring Boot = pre-mixed ingredients, you just heat and serve.

So, Spring Boot is built on top of Spring Framework but makes it much easier for beginners and professionals.

1.2 Advantages over Traditional Spring Framework

Here's why people prefer Spring Boot instead of only using Spring Framework:

  1. Less Configuration
    • In Spring, you had to write many XML files or Java config classes.
    • In Spring Boot, most of it is already done for you.
  2. Embedded Server
    • With Spring, you had to install a server (like Tomcat) separately and connect it.
    • With Spring Boot, the server comes inside the application. Just run the app, and it works.
  3. Faster Development
    • You can create a project, add a few lines of code, and run it directly.
    • No need for a long setup.
  4. Production Ready
    • Spring Boot apps have built-in tools like health checks and metrics that help in running apps in real-world production.

1.3 Core Features of Spring Boot

  1. Auto-Configuration
    • Spring Boot tries to guess what you want to set up and does it for you automatically.
    • Example: If you add a database library, Spring Boot will configure a database connection for you.
  2. Embedded Server
    • You don't need to download or set up Tomcat/Jetty separately.
    • Just run your Spring Boot application, and it starts with its own server.
  3. Starter Dependencies
    • In Spring, you had to search and add many dependencies manually. In Spring Boot, you just add one "starter dependency," and it includes everything you need.

    Example:

    • spring-boot-starter-web → adds everything for building web apps.
    • spring-boot-starter-data-jpa → adds everything for working with databases.

2. SPRING BOOT PROJECT SETUP

2.1 Creating a Project (Spring Initializr)

Spring Initializr is a free online tool provided by the Spring team to quickly create a Spring Boot project.

Steps to create a project:

  1. Go to https://start.spring.io
  2. Fill in the details:
    • Project: Maven or Gradle (choose Maven if you are a beginner)
    • Language: Java (default choice)
    • Spring Boot Version: Choose the latest stable version
    • Project Metadata:
      • Group: com.example
      • Artifact: demo
      • Name: demo
    • Packaging: Jar (default)
    • Java Version: 17 (or the one you have installed)
  3. Add dependencies: Example → Spring Web, Spring Boot DevTools
  4. Click Generate Project. A .zip file will download.
  5. Extract the zip and open the folder in your IDE (IntelliJ, Eclipse, VS Code).

This is how you create your very first Spring Boot project without writing any setup code.

2.2 Project Structure Overview

When you open your Spring Boot project, you will see a few important folders and files:

  • src/main/java → Contains your Java code (controllers, services, main app file).
  • src/main/resources → Contains configuration files (like application.properties).
  • src/test/java → For writing test cases.
  • pom.xml (or build.gradle) → Dependency management file.
  • DemoApplication.java → The main entry point of your project, which starts the Spring Boot app.

Key thing to note: Unlike traditional Java projects, you don't need to configure XML files. Spring Boot auto-manages it.

2.3 pom.xml / build.gradle basics

Spring Boot projects use Maven or Gradle for dependency management.

These files tell your project:

  • Which libraries to use
  • Which version to download
  • How to build/run the project

Example: pom.xml (Maven)


<dependencies>
    <!-- Spring Web dependency -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Spring Boot DevTools for faster development -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>
                             

Example: build.gradle (Gradle)


dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    runtimeOnly 'org.springframework.boot:spring-boot-devtools'
}
                             

3. APPLICATION ENTRY POINT

When you build a Spring Boot application, you always need a starting point. This is the place where the program begins to run. In Java, every application starts with a `main()` method.

Spring Boot adds a special annotation and structure to make this process easy.

3.1 @SpringBootApplication Annotation

@SpringBootApplication is a special annotation that tells Spring Boot:

  • a. This is the main class of the application.
  • b. It should start the Spring Boot framework.
  • c. It should look for other components (controllers, services, etc.) automatically.

This annotation is actually a combination of three other annotations:

  • @Configuration → Tells Spring that this class can have configuration (settings).
  • @EnableAutoConfiguration → Lets Spring Boot configure things automatically (like database, web server, etc.).
  • @ComponentScan → Finds and registers other classes (controllers, services, repositories) in the project.

So instead of writing all three, we just write @SpringBootApplication.

Example:


@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
                             

3.2 main() Method Explanation

Every Java application starts with a main() method.

In Spring Boot, this method also starts the SpringApplication. What happens inside?

  1. SpringApplication.run(MyApplication.class, args); is called.
  2. This line starts the Spring Boot application.
  3. It sets up the embedded server (like Tomcat).
  4. It loads all the components and configuration.
  5. Finally, it runs your application.

Key point:

  • You don't need to set up a server separately.
  • Just run this class → Your app is live on http://localhost:8080.

This way, with just a few lines, your Spring Boot project is ready to run.

4. CONFIGURATION IN SPRING BOOT

Spring Boot applications need some settings to run properly, like database details, server port, or environment-specific values. Instead of writing them directly in code, we keep them in configuration files.

4.1 application.properties vs application.yml

Spring Boot supports two main formats for configuration:

4.1.1 application.properties

Uses key=value format.

Example:


server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=1234
                             

4.1.2 application.yml

Uses YAML format (cleaner, uses indentation).

Example:


server:
  port: 8081
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb
    username: root
    password: 1234
                             

Key difference:

  • properties → simple but longer.
  • yml → cleaner and easier to read for nested settings.

4.2 Profiles (dev, test, prod)

In real projects, we use different settings for:

  • dev → Development (local system, testing features).
  • test → Testing environment.
  • prod → Production (live system used by users).

Spring Boot supports profiles using application-{profile}.properties or application-{profile}.yml.

Example:

application-dev.properties


server.port=8082
spring.datasource.url=jdbc:mysql://localhost:3306/devdb
                             

application-prod.properties


server.port=8080
spring.datasource.url=jdbc:mysql://prod-db-server:3306/proddb
                             

To activate a profile:


spring.profiles.active=dev
                             

This tells Spring Boot to use application-dev.properties.

4.3 Externalized Configuration

Spring Boot allows us to keep configuration outside the code so we can change it without modifying the application.

Places Spring Boot looks for configuration (priority order):

  1. Command line arguments
  2. Environment variables
  3. application.properties / application.yml inside project
  4. Config files outside the JAR (for production deployment)

Example: Run app with external configuration


java -jar myapp.jar --server.port=9090
                             

This will override the port defined in application.properties.

5. SPRING BOOT ANNOTATIONS

Annotations in Spring Boot are like labels or shortcuts we write in code. They tell Spring what the code should do without us writing long instructions.

5.1 Core Annotations

These are the most basic annotations that mark classes as part of the Spring system.

5.1.1 @Component

  • Used to mark a normal class as a Spring-managed class.
  • Spring will automatically create an object of this class.

@Component
public class MyHelper {
    public String sayHello() {
        return "Hello from Component!";
    }
}
                             

5.1.2 @Service

  • Similar to @Component but used for business logic.
  • Example: calculations, rules, main work of the app.

@Service
public class PaymentService {
    public void processPayment() {
        System.out.println("Payment processed!");
    }
}
                             

5.1.3 @Repository

  • Used for database work.
  • Example: saving, updating, deleting, or reading from the database.

@Repository
public class UserRepository {
    public void saveUser() {
        System.out.println("User saved in DB!");
    }
}
                             

5.1.4 @Controller

  • Used for handling web requests (from a website or user).
  • Sends back HTML pages (not JSON).

@Controller
public class HomeController {
    @GetMapping("/")
    public String homePage() {
        return "index"; // returns HTML page
    }
}
                             

5.2 REST Annotations

These are for building REST APIs (where we send and receive data, usually JSON).

5.2.1 @RestController

  • Combines @Controller and @ResponseBody.
  • Directly returns JSON or text instead of HTML.

@RestController
public class UserController {
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello from API!";
    }
}
                             

5.2.2 @GetMapping

  • Handles GET requests (fetching data).

@GetMapping("/users")
public List<String> getUsers() {
    return List.of("Rudra", "Parth", "Sourabh");
}
                             

5.2.3 @PostMapping

  • Handles POST requests (adding data).

@PostMapping("/addUser")
public String addUser(@RequestBody String name) {
    return "User added: " + name;
}
                             

5.2.4 Other REST Annotations

  • @PutMapping → Update data
  • @DeleteMapping → Delete data
  • @PatchMapping → Update partially

5.3 Dependency Injection Annotations

Dependency Injection (DI) means Spring gives you the objects you need, instead of you creating them manually.

5.3.1 @Autowired

  • Automatically injects (provides) the required object.

@Service
public class OrderService {
    @Autowired
    private PaymentService paymentService;

    public void placeOrder() {
        paymentService.processPayment();
    }
}
                             

5.3.2 @Qualifier

  • Used when there are multiple beans of the same type and you want to pick a specific one.

@Service("paypal")
public class PaypalPaymentService implements PaymentService {}

@Service("stripe")
public class StripePaymentService implements PaymentService {}

@Autowired
@Qualifier("stripe")
private PaymentService paymentService;
                             

5.4 Configuration Annotations

5.4.1 @Value

  • Injects values from application.properties or application.yml.

@Value("${app.name}")
private String appName;
                             

5.4.2 @Configuration

  • Marks a class as a configuration class (like a settings file in Java).

@Configuration
public class AppConfig {
    @Bean
    public String appMessage() {
        return "Spring Boot Rocks!";
    }
}
                             

5.4.3 @Bean

  • Creates and manages objects inside Spring.

@Bean
public MyHelper myHelper() {
    return new MyHelper();
}
                             

6. RESTFUL WEB SERVICES IN SPRING BOOT

Spring Boot makes it super easy to build RESTful APIs for web and mobile apps. REST (Representational State Transfer) is an architectural style where communication happens over HTTP using standard methods like GET, POST, PUT, DELETE.

6.1 Building REST APIs with Spring Boot

  • Spring Boot provides Spring Web Starter (spring-boot-starter-web) to create REST APIs.
  • REST controllers are usually annotated with @RestController.
  • APIs communicate using JSON by default.

Example:


@RestController
@RequestMapping("/api")
public class UserController {
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, Spring Boot REST API!";
    }
}
                             

6.2 Request Mapping

@RequestMapping

  • Maps HTTP requests to specific handler methods or classes.
  • Can be used at class-level and method-level.

@RequestMapping("/users")
public class UserController { ... }
                             

@PathVariable

  • Extracts dynamic values from the URL.

@GetMapping("/users/{id}")
public String getUser(@PathVariable int id) {
    return "User ID: " + id;
}
                             

@RequestParam

  • Extracts query parameters from the URL.

@GetMapping("/search")
public String search(@RequestParam String name) {
    return "Searching for: " + name;
}
                             

6.3 Request & Response Bodies

@RequestBody

  • Binds JSON from request body to a Java object.

@PostMapping("/users")
public User createUser(@RequestBody User user) {
    return user; // returns the same user as JSON
}
                             

@ResponseBody

  • Sends a Java object as JSON in response.
  • Included automatically with @RestController.

@GetMapping("/user")
public @ResponseBody User getUser() {
    return new User(1, "Rudra");
}
                             

6.4 Handling JSON with Jackson

  • Spring Boot automatically uses Jackson for JSON serialization and deserialization.

Converts Java objects to/from JSON without extra setup.

Example Java object:


public class User {
    private int id;
    private String name;
    // getters and setters
}
                             

API Response:


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

7. SPRING BOOT WITH DATABASES

Spring Boot is often used to build apps that work with databases. Databases help us store, update, and fetch data (like user info, products, orders, etc.).

Spring Boot makes it very easy to connect and work with databases.

7.1 Spring Data JPA Overview

  • JPA (Java Persistence API): A standard way in Java to work with databases without writing long SQL queries.
  • Spring Data JPA: A tool in Spring Boot that uses JPA and makes database tasks even simpler.
  • Instead of writing SQL, you just define methods in interfaces, and Spring Boot creates the SQL for you.

Example:


public interface UserRepository extends JpaRepository<User, Long> {
    // Automatically creates SQL: SELECT FROM user WHERE name = ?
    List<User> findByName(String name);
}
                             

Here, findByName will fetch users with a given name. You didn't write SQL, but it works!

7.2 Configuring DataSource

Spring Boot needs to know which database to connect to.

This is done inside the application.properties or application.yml file.

Example for MySQL (application.properties):


spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=1234
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
                             
  • url → database path
  • username/password → login details
  • ddl-auto=update → Spring Boot will update tables automatically if entity changes
  • show-sql=true → shows SQL in console

7.3 Defining Entities (@Entity, @Id, @GeneratedValue)

In JPA, we use Entity classes to map Java objects to database tables.

Steps:

  1. Use @Entity → tells Spring Boot this class is a table.
  2. Use @Id → marks the primary key.
  3. Use @GeneratedValue → automatically generates ID values.

Example:


import jakarta.persistence.*;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;
    // Getters & Setters
}
                             

A table called user will be created with id, name, and email. Each User object = one row in the database.

7.4 Repositories (JpaRepository, CrudRepository)

Repositories are used to talk to the database.

Instead of writing SQL, we extend JpaRepository or CrudRepository.

Example:


import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
}
                             

Now you get methods like:

  • save(user) → save data
  • findAll() → get all rows
  • findById(1L) → get row with id = 1
  • deleteById(1L) → delete row with id = 1

7.5 Query Methods & @Query

Spring Data JPA can create queries from method names OR we can write custom queries.

  • Method Name Queries:

List<User> findByEmail(String email);
                             
  • Custom Query (@Query):

@Query("SELECT u FROM User u WHERE u.name = :name")
List<User> getUsersByName(@Param("name") String name);
                             

This uses JPQL (Java Persistence Query Language).

7.6 Using H2 Database for Testing

H2 is a lightweight, in-memory database (data is stored in RAM, not in files).

It is used for testing because:

  • No setup needed.
  • Data is temporary (clears when app stops).

Configuration (application.properties):


spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
                             

Access H2 Console:

  • After running your app → go to http://localhost:8080/h2-console
  • Login with jdbc:h2:mem:testdb.

8. EXCEPTION HANDLING IN SPRING BOOT

When we build applications, things can go wrong. For example:

  • A user enters the wrong ID.
  • A file is missing.
  • A server is down.

Instead of showing a long, confusing error page, Spring Boot allows us to handle these problems in a clean way. This is called Exception Handling.

8.1 @ControllerAdvice & @ExceptionHandler

@ExceptionHandler:

  • Used to catch specific errors (exceptions) in your code.
  • Example: If someone tries to find a user by ID but the ID doesn't exist, we can "catch" that error and return a clear message.

@RestController
public class UserController {
    @GetMapping("/user/{id}")
    public String getUser(@PathVariable int id) {
        if (id == 0) {
            throw new IllegalArgumentException("Invalid User ID");
        }
        return "User found with ID: " + id;
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public String handleInvalidId(IllegalArgumentException ex) {
        return "Error: " + ex.getMessage();
    }
}
                             

Here, when the user gives ID = 0, instead of crashing, it will return: Error: Invalid User ID

@ControllerAdvice:

  • Handles errors for all controllers in one place.

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(IllegalArgumentException.class)
    public String handleIllegalArgument(IllegalArgumentException ex) {
        return "Global Error: " + ex.getMessage();
    }
}
                             

This makes your app cleaner because you don't repeat error-handling code everywhere.

8.2 Custom Error Responses

We can create our own error message format instead of plain text.

  • For example, return JSON with details like status code, message, and timestamp.

class ErrorResponse {
    private String message;
    private String time;

    public ErrorResponse(String message, String time) {
        this.message = message;
        this.time = time;
    }
    // getters
}
                             

Controller Advice Example:


@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<ErrorResponse> handleIllegalArgument(IllegalArgumentException ex) {
        ErrorResponse error = new ErrorResponse(
            ex.getMessage(),
            java.time.LocalDateTime.now().toString()
        );
        return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
    }
}
                             

If user sends wrong data →


{
  "message": "Invalid User ID",
  "time": "2025-08-25T12:30:00"
}
                             

8.3 Built-in Error Handling

Spring Boot already has default error handling.

  • If you hit an invalid URL → You'll get a JSON like:

{
  "timestamp": "2025-08-25T12:31:12.345+00:00",
  "status": 404,
  "error": "Not Found",
  "path": "/wrong-url"
}
                             
  • If your app throws an exception without handling it → You'll see a default "whitelabel error page" or JSON error.

Spring Boot makes sure your app never just "crashes" silently.

9. VALIDATION

When we create a web application, we ask users to give some input (like name, email, password). But what if they give wrong input?

Example:

  • Email without @ symbol
  • Name empty
  • Password too short

To make sure users enter correct data, Spring Boot uses Validation.

9.1 Hibernate Validator

  • Hibernate Validator is a library that helps us check if user data is correct.
  • Spring Boot has it built-in, so we don't need to add much extra code.
  • It works with annotations (special tags written above fields).

Example:


import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;

public class User {
    @NotNull
    private String name;
    @Size(min = 6, max = 12)
    private String password;
}
                             

Here:

  • @NotNull → name cannot be empty.
  • @Size(min = 6, max=12) → password should be between 6 and 12 characters.

9.2 Annotations for Validation

These are some common validation annotations:

  • @NotNull → value cannot be null (empty).
  • @Size(min, max) → value must be within given length.
  • @Email → must be a valid email format (abc@gmail.com).
  • @Pattern → match with a pattern (like only numbers or only letters).

Example:


public class Student {
    @NotNull
    private String name;
    @Email
    private String email;
    @Pattern(regexp="^[0-9]{10}$")
    private String phone;
}
                             

This means:

  • name must not be null.
  • email must look like an email.
  • phone must be exactly 10 digits.

9.3 Using Validation in Controller

To use validation, add @Valid before the request body.


import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;

@RestController
public class StudentController {
    @PostMapping("/students")
    public String addStudent(@Valid @RequestBody Student student) {
        return "Student added successfully!";
    }
}
                             

If user sends wrong data, Spring will show an error message automatically.

9.4 Global Exception Handling for Validation

Sometimes, we want to send custom error messages instead of default ones.

We can use @ControllerAdvice and @ExceptionHandler.

Example:


import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import java.util.*;

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, String>> handleValidationErrors(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getFieldErrors().forEach(error ->
            errors.put(error.getField(), error.getDefaultMessage()));
        return ResponseEntity.badRequest().body(errors);
    }
}
                             

Now, if user enters wrong input: Instead of a long error, they will get a clear message like:


{
  "email": "must be a well-formed email address",
  "phone": "must match the pattern"
}
                             

10. SPRING BOOT SECURITY (BASICS)

Spring Boot Security helps us protect our applications. For example, if you make a website, not everyone should see everything.

Some pages should only be seen by logged-in users. Spring Security makes this possible with very little setup.

10.1 Adding Spring Security Starter

To use Spring Security, we add this dependency in our pom.xml file:


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
                             

That's it! Spring Boot will automatically enable basic security.

  • After adding this, every request in your app will require login.
  • By default, Spring Boot creates a username: user and a random password shown in the console when you run the app.

10.2 Default Security Configurations

When you first run the app after adding the dependency:

  • A login page is automatically created by Spring Security.
  • You will see a generated password in the console like:

Using generated security password: 12345-abcde-xyz
                             
  • Username is always user.
  • You can log in with these details to access your application.

This is the default security setup - Spring does it for you, without writing extra code.

10.3 In-memory Authentication

Instead of using the default user account, we can create our own users in memory.

Example:


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("rudra").password("{noop}password123").roles("USER")
            .and()
            .withUser("admin").password("{noop}admin123").roles("ADMIN");
    }
}
                             

Explanation:

  • withUser("rudra") → creates a user with username rudra.
  • password("{noop}password123") → password is password123. ({noop} means no encoding).
  • roles("USER") → gives this user the role USER.

Now you can log in with your own username and password.

10.4 Basic Authentication vs JWT (Intro)

There are two main ways to secure an app:

  1. Basic Authentication
    • Username and password are sent with each request.
    • Very simple to use.
    • But less secure because credentials are shared every time.
    • Good for small projects or testing.
  2. JWT (JSON Web Token)
    • After login, server gives you a token (like an ID card).
    • You send this token instead of username/password.
    • More secure and widely used in real-world apps.
    • Great for mobile apps, web apps, and APIs.

Example flow of JWT:

  • You log in with username/password.
  • Server gives you a token.
  • You use this token for future requests.
  • Server checks the token to verify you.

11. SPRING BOOT DEVTOOLS

Spring Boot DevTools is a special tool that helps developers save time while coding. Normally, every time you make a small change in your code, you have to stop the server and restart it to see the effect.

DevTools makes this process easier by doing it for you automatically.

11.1 Auto Restart

  • When you change something in your code (for example, a Java class or configuration file), DevTools automatically restarts the application.
  • You don't need to manually stop and start the server every time.
  • This saves a lot of time during development.
  • Example: If you change a method inside a controller and save the file, the application will restart automatically with the updated code.

11.2 Live Reload

Live Reload helps when you are working on the front-end part (like HTML, CSS, or JavaScript) in your Spring Boot application.

  • It updates the browser page automatically after you save your changes.
  • This means you don't have to refresh the browser again and again.
  • Example: If you edit an HTML file and save it, the browser will reload itself to show the latest changes.

11.3 Debugging Support

  • DevTools also provides better debugging support during development.
  • It keeps some parts of the application (like static resources and caches) from restarting unnecessarily, so you can debug faster.
  • Example: If you are fixing a bug in a controller, you can quickly change the code, save it, and test again without waiting too long for the application to restart.

12. ACTUATOR & MONITORING

Spring Boot Actuator is a tool that helps developers check the health, performance, and important details of their applications while they are running.

Think of it like a dashboard for your app that shows what is happening inside, without opening the code every time.

12.1 Enabling Actuator

To start using Actuator, you first add the Actuator dependency in your pom.xml (Maven) or build.gradle (Gradle).

Maven Dependency:


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
                             

After adding, Actuator is automatically enabled with some default endpoints.

You can also control which endpoints are available in your application.properties file.

Example:


management.endpoints.web.exposure.include=health,info,metrics
                             

This means only the health, info, and metrics endpoints will be accessible.

12.2 Common Endpoints

Spring Boot Actuator provides many endpoints. Here are the most important ones for beginners:

12.2.1 /health

  • Shows the health status of your application.

Example:


{
  "status": "UP"
}
                             
  • "UP" means everything is working fine.
  • "DOWN" means something is wrong.

12.2.2 /info

  • Displays basic information about your application like version, name, and description.
  • You can customize it by adding values in application.properties:

info.app.name=My Spring Boot App
info.app.version=1.0.0
info.app.description=This is my first Spring Boot project
                             

When you visit /info, you may see:


{
  "app": {
    "name": "My Spring Boot App",
    "version": "1.0.0",
    "description": "This is my first Spring Boot project"
  }
}
                             

12.2.3 /metrics

  • Shows important numbers (metrics) about your app.

Example:

  • Memory usage
  • Number of active threads
  • JVM (Java Virtual Machine) stats
  • HTTP request counts

Visiting /metrics gives a list of metrics, for example:


{
  "names": [
    "jvm.memory.used",
    "http.server.requests",
    "system.cpu.usage"
  ]
}
                             

You can also check details of one metric, like: /metrics/system.cpu.usage

12.3 Customizing Actuator Endpoints

You don't always want to show all details of your app for security reasons. Spring Boot allows you to customize Actuator endpoints.

12.3.1 Enable All Endpoints


management.endpoints.web.exposure.include=*
                             

This will allow every endpoint (not recommended for production).

12.3.2 Exclude Specific Endpoints


management.endpoints.web.exposure.exclude=env,beans
                             

This hides env and beans endpoints.

12.3.3 Change Actuator Base Path

  • By default, all endpoints are available at /actuator/.

For example:

  • /actuator/health
  • /actuator/info

You can change this prefix:


management.endpoints.web.base-path=/monitor
                             

Now the endpoints will be:

  • /monitor/health
  • /monitor/info

13. LOGGING IN SPRING BOOT

Logging helps you track what your application is doing. Think of it as a notebook where your app writes down messages about what is happening inside.

This is very useful for debugging problems and understanding the flow of your program.

13.1 Default Logging (Spring Boot Starter Logging)

  • By default, Spring Boot comes with Spring Boot Starter Logging.
  • It uses Logback as the logging framework.
  • You don't need to add anything extra; logging is already set up when you create a Spring Boot project.

Example:


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyLoggerExample implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(MyLoggerExample.class);

    @Override
    public void run(String... args) {
        logger.info("Application has started!");
        logger.debug("This is a debug message");
        logger.error("Oops, something went wrong!");
    }
}
                             

When you run this app, Spring Boot will automatically print logs to the console.

13.2 Log Levels (TRACE, DEBUG, INFO, WARN, ERROR)

Spring Boot supports different log levels. These levels decide how detailed the logging will be.

  1. TRACE - Very detailed, step-by-step logs. Usually used for deep debugging.
  2. DEBUG - Helpful messages for developers to understand what's happening.
  3. INFO - General information, like app startup messages.
  4. WARN - Warnings about things that may cause issues later.
  5. ERROR - Errors when something has gone wrong.

Example Configuration in application.properties:


logging.level.root=INFO
logging.level.com.example.myapp=DEBUG
                             
  • logging.level.root → Sets the default log level for the whole app.
  • logging.level.com.example.myapp → Sets log level for a specific package.

If you set DEBUG, you'll see more detailed logs. If you set ERROR, only errors will be shown.

13.3 External Log Configurations

Sometimes, you want to customize logging more deeply, like:

  • Change the log pattern (how logs look).
  • Save logs to a file instead of console.
  • Control logging per environment (dev, test, prod).

Spring Boot supports external log configuration files like:

  • logback-spring.xml
  • logback.xml
  • log4j2-spring.xml

Example: Save logs into a file (application.properties):


# Save logs into a file
logging.file.name=app.log

# Change log pattern
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n
                             

This will create a file app.log in your project folder and write logs there.

Example: Logback XML (logback-spring.xml):


<configuration>
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>logs/myapp.log</file>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} [thread] %-5level %logger{36} %msg%n</pattern>
        </encoder>
    </appender>
    <root level="INFO">
        <appender-ref ref="FILE" />
    </root>
</configuration>
                             

This configuration writes all logs into logs/myapp.log with a custom format.

14. TESTING IN SPRING BOOT

Testing ensures that your application works as expected and helps maintain stability when code changes. Spring Boot provides built-in testing support with JUnit, Mockito, and MockMvc.

14.1 Unit Testing with JUnit & Mockito

  • Unit Testing focuses on testing individual methods or classes in isolation.
  • JUnit 5 is the default testing framework used in Spring Boot projects.
  • Mockito is used for creating mock objects to simulate dependencies.

Example - Unit Test with Mockito:


@SpringBootTest
class UserServiceTest {
    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private UserService userService;

    @Test
    void testGetUserById() {
        User user = new User(1L, "John");
        Mockito.when(userRepository.findById(1L)).thenReturn(Optional.of(user));

        User result = userService.getUserById(1L);

        assertEquals("John", result.getName());
    }
}
                             

Key Points:

  • @Mock: Creates mock object.
  • @InjectMocks: Injects mocked dependencies into the service.
  • assertEquals: Validates expected vs actual result.

14.2 Integration Testing with @SpringBootTest

  • Integration testing checks how different parts of the application work together.
  • @SpringBootTest loads the full application context.

Example - Integration Test:


@SpringBootTest
class ApplicationIntegrationTest {
    @Autowired
    private UserService userService;

    @Test
    void testUserCreation() {
        User user = new User(null, "Alice");
        User savedUser = userService.saveUser(user);

        assertNotNull(savedUser.getId());
        assertEquals("Alice", savedUser.getName());
    }
}
                             

Key Points:

  • @SpringBootTest: Boots up the application context.
  • Can test repositories, services, and controllers working together.

14.3 Testing REST APIs with MockMvc

MockMvc is used to test Spring MVC controllers without starting the full server.

It simulates HTTP requests and validates responses.

Example - REST API Test:


@WebMvcTest(UserController.class)
class UserControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @Test
    void testGetUserById() throws Exception {
        User user = new User(1L, "Bob");
        Mockito.when(userService.getUserById(1L)).thenReturn(user);

        mockMvc.perform(get("/users/1"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.name").value("Bob"));
    }
}
                             

Key Points:

  • @WebMvcTest: Loads only the web layer (controllers).
  • mockMvc.perform(): Simulates HTTP requests (GET, POST, PUT, DELETE).
  • .andExpect(): Validates HTTP status and JSON response.

15. SPRING BOOT WITH FRONTEND

Spring Boot can work with frontend applications in multiple ways:

15.1. Serving Static Content (/static, /public)

  • Spring Boot automatically serves static resources (like HTML, CSS, JS, and images) placed inside certain directories.
  • Default locations inside src/main/resources/ are:
    • /static/
    • /public/
    • /resources/
    • /META-INF/resources/

Example:

  • If you place a file src/main/resources/static/index.html, it can be accessed directly at:

http://localhost:8080/index.html
                             

This is useful for small frontend projects or simple websites bundled directly with Spring Boot.

15.2. Thymeleaf Integration

  • Thymeleaf is a template engine used with Spring Boot for server-side rendering.
  • It allows you to dynamically render HTML pages with data from the backend.
  • Add dependency in pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
                             
  • Create templates inside src/main/resources/templates.

Example controller:


@Controller
public class HomeController {
    @GetMapping("/welcome")
    public String welcome(Model model) {
        model.addAttribute("message", "Hello, Spring Boot with Thymeleaf!");
        return "welcome"; // maps to welcome.html in templates
    }
}
                             

Example Thymeleaf template (welcome.html):


<html>
<body>
    <h1 th:text="${message}"></h1>
</body>
</html>
                             

Best for: building dynamic, server-rendered web applications.

15.3 Connecting Spring Boot APIs with React/Angular

  • Instead of server-side rendering, you can use Spring Boot as a backend API and React/Angular as the frontend.

Setup:

  • Spring Boot exposes REST APIs (/api/...).
  • React/Angular consumes them using fetch or Axios.

Example Spring Boot REST API:


@RestController
@RequestMapping("/api")
public class UserController {
    @GetMapping("/users")
    public List<String> getUsers() {
        return List.of("Alice", "Bob", "Charlie");
    }
}
                             

Example React API call:


useEffect(() => {
    fetch("http://localhost:8080/api/users")
        .then(res => res.json())
        .then(data => console.log(data));
}, []);
                             

Deployment:

  • Option 1: Serve React/Angular build files from Spring Boot (/static).
  • Option 2: Deploy backend and frontend separately and connect via API.

16. DEPLOYMENT

Deployment in Spring Boot is the process of making your application available to end-users.

Spring Boot simplifies deployment with its embedded server support and compatibility with multiple environments like standalone servers and cloud platforms.

16.1 Running JAR with Embedded Tomcat

  • Spring Boot creates an executable JAR that includes the application code, dependencies, and an embedded server (like Tomcat, Jetty, or Undertow).
  • No need to install a separate Tomcat server. You can directly run the app using:

java -jar myapp-0.0.1-SNAPSHOT.jar
                             

Advantages:

  • Easy portability (just need Java installed).
  • Reduced deployment complexity.
  • Perfect for microservices.

16.2 Packaging as WAR

  • If your organization still uses external servers (like standalone Tomcat, WebSphere, or JBoss), you can package your Spring Boot application as a WAR file.

Steps:

  1. In pom.xml, change packaging type:

<packaging>war</packaging>
                             
  1. Extend SpringBootServletInitializer in your main application class:

@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(MyApplication.class);
    }
}
                             
  1. Deploy the generated WAR to your external server.

Use Case: Legacy environments or when multiple apps share the same app server.

16.3 Deploying to Cloud (Heroku, AWS, Azure basics)

(a) Heroku Deployment

  • Heroku is beginner-friendly for Spring Boot deployment.

Steps:

  1. Install Heroku CLI.
  2. Create a new Heroku app:

heroku create my-spring-app
                             
  1. Push your code:

git push heroku main
                             

Heroku detects it's a Spring Boot app (via Procfile) and deploys automatically.

(b) AWS Deployment (Elastic Beanstalk / EC2)

  • Elastic Beanstalk: Upload JAR/WAR, and AWS handles provisioning servers, load balancing, and scaling.
  • EC2 Instance: Manually configure Java, upload JAR, and run using java -jar.
  • Great for production-grade deployments with full control.

(c) Azure Deployment

  • Spring Boot apps can be deployed to Azure App Service.

Steps:

  1. Package your JAR.
  2. Use Azure CLI to deploy:

az webapp create --resource-group myGroup --plan myPlan --name mySpringApp --deployment-source-url 
                             

Provides managed hosting, scaling, and integration with Azure services.

17. ADVANCED FEATURES (OPTIONAL FOR BEGINNERS)

These features go beyond the basics and are often used in real-world enterprise applications. Beginners don't need them immediately, but knowing the basics can help prepare for advanced projects.

17.1 Scheduling Tasks (@Scheduled)

  • Spring Boot allows you to run tasks at specific intervals or times using the @Scheduled annotation.

Enable Scheduling: Add @EnableScheduling in your main application class.

Use Cases: Sending email reminders, clearing temporary files, fetching data at intervals.

Example:


@SpringBootApplication
@EnableScheduling
public class MyApp {}

@Component
public class ScheduledTasks {
    @Scheduled(fixedRate = 5000) // runs every 5 seconds
    public void task() {
        System.out.println("Task executed at: " + LocalDateTime.now());
    }
}
                             

17.2 Asynchronous Calls (@Async)

  • By default, Spring executes methods synchronously (one after another). With @Async, methods can run in the background.

Enable Async: Add @EnableAsync in your main class.

Use Cases: Sending notifications, processing files, long-running tasks without blocking.

Example:


@SpringBootApplication
@EnableAsync
public class MyApp {}

@Service
public class NotificationService {
    @Async
    public void sendEmail(String user) {
        System.out.println("Sending email to " + user + " from " + Thread.currentThread().getName());
    }
}
                             

17.3 Messaging with RabbitMQ/Kafka (Intro)

  • Spring Boot supports message brokers like RabbitMQ and Kafka for asynchronous communication between microservices.
  • RabbitMQ: Message queue system, ensures messages are delivered.
  • Kafka: Distributed event streaming platform for high-volume data.

Use Cases:

  • Order processing systems (e.g., e-commerce).
  • Logging & monitoring events.
  • Communication between microservices.

Example (RabbitMQ):


@Component
public class MessageProducer {
    @Autowired
    private AmqpTemplate template;

    public void send(String msg) {
        template.convertAndSend("queueName", msg);
    }
}
                             

17.4 Spring Boot with Microservices (Intro to Spring Cloud)

Spring Boot can be extended with Spring Cloud to build microservices.

What are Microservices?

  • Instead of one large application (monolith), you split it into small services that communicate via APIs.

Spring Cloud Features:

  • Service Discovery (Eureka) → Services find each other dynamically.
  • API Gateway (Zuul / Spring Cloud Gateway) → Routes traffic to services.
  • Config Server → Centralized configuration management.
  • Circuit Breaker (Resilience4j/Hystrix) → Handles failures gracefully.

Example Use Case:

  • User Service → Manages users.
  • Order Service → Manages orders.
  • Both communicate via REST APIs or messaging (Kafka/RabbitMQ).

18. BEST PRACTICES

18.1 Directory Structure

Spring Boot encourages a well-organized package structure to keep the application modular and maintainable.

A common structure:


com.example.myapp
├── controller  - REST Controllers
├── service     - Business logic
├── repository  - Database interactions (JPA/Hibernate)
├── model/entity - Entities/POJOs
├── dto         - Data Transfer Objects
├── config      - Configuration classes
└── exception   - Custom exception handling
                             

Keep main application class in the root package to enable component scanning across sub-packages.

18.2 Exception Handling Standards

  • Avoid exposing raw exceptions directly to clients.
  • Use @ControllerAdvice + @ExceptionHandler for global exception handling.
  • Return meaningful error messages in standard format (e.g., JSON with timestamp, message, status).

Example:


@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
    }
}
                             

Always log exceptions for debugging but avoid exposing sensitive details to users.

18.3 DTO & Service Layer Usage

DTO (Data Transfer Objects):

  • Used to separate API response/request models from database entities.
  • Prevents exposing internal database structures to clients.
  • Keeps flexibility in case database schema changes.

Example: UserEntity vs UserDTO.

Service Layer:

  • Acts as the business logic layer between Controllers and Repositories.
  • Keeps Controllers lightweight (only handling request/response).

Example:


@Service
public class UserService {
    private final UserRepository repo;

    public UserService(UserRepository repo) {
        this.repo = repo;
    }

    public UserDTO getUser(Long id) {
        UserEntity entity = repo.findById(id).orElseThrow();
        return new UserDTO(entity.getId(), entity.getName());
    }
}
                             

18.4 Configuration Management

  • Store configurations in application.properties or application.yml.
  • Use profiles (application-dev.yml, application-prod.yml) for environment-specific settings.
  • Keep sensitive data (API keys, DB passwords) out of source code. Use:
    • Environment variables
    • application.yml with placeholders (${DB_PASSWORD})
    • Externalized config servers (e.g., Spring Cloud Config)

Example:


spring:
  profiles: dev
  datasource:
    url: jdbc:mysql://localhost:3306/devdb
    username: root
    password: ${DB_PASSWORD}
                             

19. QUICK REFERENCE

19.1 Most Common Annotations

Spring Boot provides a wide set of annotations to simplify development. Here are the most frequently used ones:

  • @SpringBootApplication
    • Combines @Configuration, @EnableAutoConfiguration, and @ComponentScan.
    • Entry point of a Spring Boot application.
  • @RestController
    • Combines @Controller and @ResponseBody.
    • Used for REST APIs (returns JSON/XML instead of views).
  • @RequestMapping / @GetMapping / @PostMapping / @PutMapping / @DeleteMapping
    • Map HTTP requests to handler methods.

    Example:

    
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello World!";
    }
                                         
  • @Autowired
    • Automatically injects beans (dependencies) into a class.
  • @Service, @Repository, @Controller, @Component
    • Stereotype annotations used to mark classes for component scanning.
  • @Entity & @Table
    • Marks a class as a JPA entity (database table).
  • @Id & @GeneratedValue
    • Used for primary keys in JPA.
  • @Configuration & @Bean
    • Define custom beans inside a configuration class.
  • @Value & @ConfigurationProperties
    • Bind external properties (from application.properties or application.yml).
  • @Transactional
    • Ensures database operations execute within a transaction.

19.2 Important CLI Commands

Spring Boot provides CLI (Command Line Interface) commands for quick execution and testing.

  1. Run Application

mvn spring-boot:run
                             

or


gradle bootRun
                             
  1. Build Executable JAR

mvn clean package
                             

Then run:


java -jar target/appname-0.0.1-SNAPSHOT.jar
                             
  1. Check Version

spring --version
                             
  1. Initialize Project with Spring CLI

spring init --dependencies=web,data-jpa,mysql demo-app
                             
  1. Run with Different Profile

java -jar app.jar --spring.profiles.active=dev
                             

19.3 Frequently Used Properties

Defined inside application.properties or application.yml.

  1. Server Configurations

server.port=8081
server.servlet.context-path=/myapp
                             
  1. Database Configurations

spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
                             
  1. Profiles

spring.profiles.active=dev
                             
  1. Logging

logging.level.org.springframework=INFO
logging.level.com.myapp=DEBUG
logging.file.name=app.log
                             
  1. Multipart File Uploads

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
                             
  1. Custom Properties

app.title=My Spring Boot App
app.version=1.0.0
                             

Download the Full Spring Boot Cheatsheet PDF!

Click the button below to get your copy of this Spring Boot cheatsheet in a handy PDF format. Download will be ready in 5 seconds.

Ready for the DSA Cheatsheet?

Explore our comprehensive Data Structures and Algorithms Cheatsheet to enhance your programming and problem-solving skills. Click below to dive in!

Other Cheatsheets

Stay Updated

Receive coding tips and resources updates. No spam.

We respect your privacy. Unsubscribe at any time.