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:
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.
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.
Faster Development
You can create a project, add a few lines of code, and run it directly.
No need for a long setup.
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
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.
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.
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.
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>
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?
SpringApplication.run(MyApplication.class, args); is called.
This line starts the Spring Boot application.
It sets up the embedded server (like Tomcat).
It loads all the components and configuration.
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:
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");
}
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;
}
@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.
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.
@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:
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:
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.
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).
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.
@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
}
}
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:
In pom.xml, change packaging type:
<packaging>war</packaging>
Extend SpringBootServletInitializer in your main application class:
@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(MyApplication.class);
}
}
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:
Install Heroku CLI.
Create a new Heroku app:
heroku create my-spring-app
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:
Package your JAR.
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.
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.