Spring Boot in One Shot – Ultimate Cheat Sheet
A clear and practical revision guide covering the most important Spring Boot concepts in one place. From project setup and auto-configuration to REST APIs, JPA, security basics, and deployment — everything is explained in a simple, structured way. Perfect for interviews, quick revision, or anyone who wants to understand how Spring Boot applications are built and run in real projects.
Shreyash Gurav
March 02, 2026
16 min read
Spring Boot in One Shot — The Ultimate CheatSheet
Master Spring Boot from zero to hero with this comprehensive, no-fluff reference. Whether you're just starting out, preparing for interviews, or building a project, this cheat sheet packs everything you need — annotations, config, security, JPA, testing, deployment — with practical examples you can use immediately. No prior Spring experience required!
1. What is Spring Boot?#
Spring Boot is an extension of the Spring Framework that eliminates boilerplate configuration and setup. It provides embedded servers, auto-configuration, and production-ready features so developers can focus entirely on business logic rather than infrastructure.
Key Benefits:
- Zero XML configuration
- Embedded Tomcat, Jetty, or Undertow
- Auto-configures beans based on classpath
- Production monitoring via Actuator
- Single executable JAR deployment
Spring Boot vs Spring Framework:
| Feature | Spring Framework | Spring Boot |
|---|---|---|
| Configuration | Manual XML/Java | Auto-configured |
| Server | External Tomcat | Embedded |
| Setup Time | High | Very low |
| Dependencies | Manual management | Starter bundles |
| Learning Curve | Steep | Beginner friendly |
2. Project Structure#
A standard Spring Boot project follows a layered package structure. Each folder represents a layer with a single responsibility, making the codebase easy to navigate and maintain.
3. Main Application Class#
@SpringBootApplication is a convenience annotation that combines three annotations into one. When SpringApplication.run() is called, it creates the ApplicationContext, triggers auto-configuration, and starts the embedded server.
@SpringBootApplication internally combines:
@Configuration— marks class as bean source@EnableAutoConfiguration— enables auto-config@ComponentScan— scans current package and sub-packages

4. Spring Starters#
Starters are pre-packaged dependency bundles for specific features. Instead of manually finding and matching compatible library versions, you add one starter and Spring Boot handles the rest.
| Starter | Purpose |
|---|---|
spring-boot-starter-web | REST APIs and web apps |
spring-boot-starter-data-jpa | JPA and Hibernate |
spring-boot-starter-security | Authentication and authorization |
spring-boot-starter-test | JUnit, Mockito, MockMvc |
spring-boot-starter-actuator | Monitoring and health checks |
spring-boot-starter-validation | Bean validation |
5. Core Spring Concepts#
Inversion of Control (IoC)#
IoC means Spring takes control of object creation instead of you using the new keyword manually. The Spring IoC container creates, wires, and manages all objects (beans) throughout the application lifecycle.
Dependency Injection (DI)#
DI is the mechanism through which IoC is implemented. Spring injects required dependencies into a class automatically, removing tight coupling between components.
Three types of DI:
| Type | Testable | Immutable | Recommended |
|---|---|---|---|
| Constructor | Yes | Yes | Yes |
| Setter | Partial | No | Optional use |
| Field | No | No | No |
Beans#
A Bean is any Java object created and managed by the Spring IoC container. You register beans using stereotype annotations or @Bean inside a @Configuration class.
Stereotype Annotations#
| Annotation | Layer | Extra Behavior |
|---|---|---|
@Component | Any | Generic bean |
@Service | Business | Semantic clarity |
@Repository | Persistence | DB exception translation |
@Controller | Presentation | Returns views |
@RestController | Presentation | Returns JSON directly |
6. Configuration#
Spring Boot externalizes configuration so the same JAR can run in dev, test, and production without code changes. Configuration sources follow a priority order — higher sources override lower ones.
Priority order (highest to lowest):
- Command line arguments
- Java system properties
- Environment variables
application.propertiesorapplication.yml- Default properties
application.properties:
application.yml (same config, hierarchical format):
Profiles#
Profiles let you define environment-specific configuration files. When a profile is active, Spring Boot loads both application.properties and the profile-specific file, with the profile file taking priority.
Create separate files per environment:
application-dev.propertiesapplication-prod.propertiesapplication-test.properties

7. REST API Development#
Spring Boot makes building REST APIs simple using annotation-based controllers and automatic JSON serialization via Jackson. REST follows stateless communication where each request contains all the information needed to process it.
HTTP Method to Annotation mapping:
| Annotation | HTTP Method | Use Case |
|---|---|---|
@GetMapping | GET | Fetch resource |
@PostMapping | POST | Create resource |
@PutMapping | PUT | Full update |
@PatchMapping | PATCH | Partial update |
@DeleteMapping | DELETE | Remove resource |
Complete CRUD Controller:
Request data extraction:
HTTP Status Codes:
| Code | Meaning | When to use |
|---|---|---|
| 200 | OK | Successful GET, PUT |
| 201 | Created | Successful POST |
| 204 | No Content | Successful DELETE |
| 400 | Bad Request | Validation failed |
| 401 | Unauthorized | Not authenticated |
| 403 | Forbidden | Not authorized |
| 404 | Not Found | Resource missing |
| 500 | Server Error | Unexpected failure |
8. Validation and Exception Handling#
Bean Validation API provides declarative constraints on request objects. When @Valid is used in a controller, Spring automatically validates the incoming data before the method executes and throws MethodArgumentNotValidException if it fails.
Validation annotations:
| Annotation | Purpose |
|---|---|
@NotNull | Field must not be null |
@NotBlank | String must not be empty |
@Email | Must be valid email format |
@Size(min, max) | String length range |
@Min / @Max | Numeric range |
@Pattern(regexp) | Must match regex |
DTO with validation:
Global Exception Handler:
@RestControllerAdvice centralizes exception handling across all controllers. Without it, Spring returns ugly stack traces. With it, every error returns a clean, consistent JSON response.
9. Database Integration — Spring Data JPA#
Spring Data JPA sits on top of JPA (specification) and Hibernate (implementation) to eliminate manual SQL and ResultSet handling. You define an interface, and Spring generates the full implementation at runtime.
Entity Mapping#
Primary Key Generation Strategies:
| Strategy | Description | Best For |
|---|---|---|
IDENTITY | DB auto-increment | MySQL, PostgreSQL |
SEQUENCE | DB sequence object | Oracle, PostgreSQL |
AUTO | JPA picks strategy | Quick prototyping |
TABLE | Separate ID table | Rarely used |
Repository Layer#
Pagination and Sorting:
Entity Relationships#
One-to-One:
One-to-Many / Many-to-One:
Many-to-Many:
Fetch Types:
| Type | Behavior | Default for |
|---|---|---|
EAGER | Loads related data immediately | @OneToOne, @ManyToOne |
LAZY | Loads related data only when accessed | @OneToMany, @ManyToMany |
Prefer LAZY for collections to avoid loading unnecessary data.
Avoid infinite recursion in bidirectional relationships:

10. Transaction Management#
Transactions ensure that a group of database operations either all succeed or all fail together, maintaining data integrity. Spring Boot provides declarative transaction management through the @Transactional annotation.
Propagation Types:
| Propagation | Behavior |
|---|---|
REQUIRED | Join existing or create new (default) |
REQUIRES_NEW | Always creates new, suspends existing |
NESTED | Runs in nested transaction |
MANDATORY | Must have existing transaction or throws |
NEVER | Must not have transaction or throws |
SUPPORTS | Runs in transaction if one exists |
NOT_SUPPORTED | Suspends existing, runs non-transactionally |
Isolation Levels:
| Level | Dirty Read | Non-Repeatable Read | Phantom Read |
|---|---|---|---|
READ_UNCOMMITTED | Yes | Yes | Yes |
READ_COMMITTED | No | Yes | Yes |
REPEATABLE_READ | No | No | Yes |
SERIALIZABLE | No | No | No |
11. Async Processing#
@Async allows methods to run in a separate thread so the caller doesn't wait for completion. It is useful for sending emails, notifications, or any long-running task that doesn't need to block the main request.
12. Spring Security#
Spring Security intercepts every incoming request through a filter chain before it reaches your controllers. It handles authentication (who are you?) and authorization (what can you do?) in a structured, extensible way.
Security Filter Chain#

13. JWT Authentication#
JWT (JSON Web Token) is a stateless authentication mechanism where the server issues a signed token after login. The client stores the token and sends it with every request — no session storage needed on the server.
JWT Structure:
Never store passwords or secrets in the payload — it is Base64 encoded, not encrypted.
JWT Filter:

14. CORS Configuration#
CORS is a browser security restriction that blocks frontend apps on a different origin from calling your backend. The server must explicitly tell the browser which origins, methods, and headers are allowed.
15. Logging with @Slf4j#
Spring Boot uses SLF4J with Logback by default. The @Slf4j annotation from Lombok auto-generates a logger instance so you can start logging immediately without boilerplate.
Log Levels (lowest to highest priority):
| Level | Use For |
|---|---|
TRACE | Extremely detailed diagnostic info |
DEBUG | Variable values, method flow |
INFO | Business events, app startup |
WARN | Recoverable issues, deprecated usage |
ERROR | Failures, exceptions |
Configuration:
Best practices:
- Always use parameterized logging
log.info("User: {}", name)not string concatenation - Never log passwords, tokens, or card numbers
- Always include the exception object in
log.error()for stack trace - Use
DEBUGandTRACEonly — neverINFO— for internal flow details
16. Testing#
Spring Boot provides excellent testing support out of the box. Following the testing pyramid — many unit tests, some integration tests, few end-to-end tests — gives you fast feedback with reliable coverage.
Unit Testing with Mockito#
Unit tests verify a single class in isolation. Mock all dependencies so the test only exercises the class under test.
Controller Testing with MockMvc#
Repository Testing with @DataJpaTest#
Testing annotations summary:
| Annotation | Loads | Use For |
|---|---|---|
@SpringBootTest | Full context | Integration tests |
@WebMvcTest | Web layer only | Controller tests |
@DataJpaTest | JPA layer only | Repository tests |
@ExtendWith(MockitoExtension.class) | Nothing | Pure unit tests |
17. Spring Boot Actuator#
Actuator exposes production-ready endpoints for health checks, metrics, and application info. It is essential for monitoring applications in production environments and integrates easily with tools like Prometheus and Grafana.
Common Endpoints:
| Endpoint | Description |
|---|---|
/actuator/health | App and dependency health status |
/actuator/info | App version and metadata |
/actuator/metrics | JVM, CPU, request metrics |
/actuator/env | All environment properties |
/actuator/loggers | View and change log levels at runtime |
/actuator/beans | All registered Spring beans |
/actuator/mappings | All request mapping paths |
/actuator/threaddump | Current thread states |

18. Spring Boot DevTools#
Spring Boot DevTools enhances the development experience by providing automatic restarts, live reload, and development-time optimizations. It should never be used in production — it's strictly a development dependency.
xml
Key Features#
| Feature | What It Does | Developer Benefit |
|---|---|---|
| Automatic Restart | Restarts app when classpath files change | Instant feedback after code changes |
| LiveReload | Triggers browser refresh automatically | See UI changes immediately |
| Cache Disabling | Turns off template/thymeleaf caching | Templates update without restart |
| Property Defaults | Sets dev-friendly defaults | No manual config needed |
| Remote Debugging | Optional remote update support | Debug deployed apps |
19. Caching#
Caching stores the result of expensive operations (database queries, API calls, computations) so repeated requests return instantly without re-executing the underlying logic. Spring Boot integrates with multiple cache providers through a unified abstraction layer.
Enable caching in your main config:
Core caching annotations:
| Annotation | Behavior |
|---|---|
@Cacheable | Returns cached result if exists, otherwise executes and caches |
@CachePut | Always executes and updates the cache |
@CacheEvict | Removes entry (or all entries) from cache |
@Caching | Groups multiple cache annotations on one method |
Practical service example:
Cache providers:
| Provider | Best For | Dependency |
|---|---|---|
ConcurrentHashMap | Dev/testing only | Built-in (default) |
| Caffeine | Single-instance apps, high performance | spring-boot-starter-cache + caffeine |
| Redis | Distributed apps, multiple instances | spring-boot-starter-data-redis |
| EhCache | JVM-local, rich config | ehcache |
Redis setup :
Conditional caching:
Best practices:
- Always set a TTL (time-to-live) — unbounded caches grow until OutOfMemoryError
- Use Redis in any multi-instance deployment — in-memory caches are per-JVM and go out of sync
- Cache at the service layer, never the controller or repository layer
- Keep cached objects serializable — required for Redis and most distributed providers
- Use
@CacheEvicton every write operation that modifies cached data, or you'll serve stale results
20. API Documentation with Swagger / OpenAPI#
Springdoc OpenAPI auto-generates interactive API documentation from your existing controller annotations. It requires zero extra configuration to get started.
After adding the dependency:
- Swagger UI:
http://localhost:8080/swagger-ui.html - OpenAPI JSON:
http://localhost:8080/v3/api-docs
Allow these paths in your security config:
21. Build and Deployment#
Spring Boot packages the entire application — including the embedded server — into a single executable JAR. This makes deployment simple and consistent across all environments.
Build commands:
Run the JAR:
Dockerfile:
Quick Reference — Most Used Annotations#
| Annotation | Purpose |
|---|---|
@SpringBootApplication | Bootstrap the application |
@RestController | REST controller, returns JSON |
@RequestMapping | Base URL mapping |
@GetMapping / @PostMapping etc. | HTTP method mapping |
@PathVariable | Extract from URL path |
@RequestParam | Extract from query string |
@RequestBody | Bind JSON body to object |
@Valid | Trigger bean validation |
@Service | Business logic bean |
@Repository | Data access bean |
@Component | Generic bean |
@Autowired | Inject dependency |
@Value | Inject config property |
@Entity | JPA entity (maps to table) |
@Transactional | Transaction boundary |
@Async | Run in separate thread |
@Slf4j | Auto-generate logger |
@RestControllerAdvice | Global exception handler |
@ExceptionHandler | Handle specific exception |
@Configuration | Bean definition class |
@Bean | Register method return as bean |
@Profile | Activate in specific profile |
@DataJpaTest | Slice test for JPA layer |
@WebMvcTest | Slice test for web layer |
@MockBean | Spring-aware mock in tests |
Conclusion#
This Spring Boot cheat sheet covers everything from core concepts to production deployment in a concise, practical format. Master these fundamentals and you'll be ready to build production-ready applications with confidence. If you found this helpful, share it with your friends and colleagues — good knowledge grows when shared!
Want to Master Spring Boot and Land Your Dream Job?
Struggling with coding interviews? Learn Data Structures & Algorithms (DSA) with our expert-led course. Build strong problem-solving skills, write optimized code, and crack top tech interviews with ease
Learn more

