The standard backend framework of the Java ecosystem. A practice-focused guide covering IoC/DI, REST APIs, JPA, Spring Security, testing, and Docker deployment.
Intermediate
Updated Oct 1, 2026
~8 min read
13 sections
8 code examples
Web IDE lab included
π
Spring Boot Web IDE
Run code in the browser with nothing to install and learn through step-by-step examples.
Understanding Spring Boot as a real-world workflow
The standard backend framework of the Java ecosystem. A practice-focused guide covering IoC/DI, REST APIs, JPA, Spring Security, testing, and Docker deployment. Rather than listing concepts, this guide is organized so you can follow the content in the order you have to make decisions on a real project.
Key perspective
Backend / systems development
Before syntax, pin down the boundaries a request crosses: validation, processing, storage, and response.
REST API serversJPA/Hibernate ORMSpring Security JWTMSA backends
Architecture diagrams
To make what you read stick, it helps to capture the flow as a picture first. The two diagrams below are reference maps you can keep coming back to while learning Spring Boot.
Learning flow
Rendering diagramβ¦
Architecture view
Rendering diagramβ¦
What is Spring Boot?
When you first open Spring Boot, the big picture matters more than individual commands. This section starts with the problems the concepts ahead were created to solve.
Spring Boot is a framework that provides auto-configuration and an embedded server, so you can build production-grade applications quickly with no complex XML configuration.
Feature
Description
Auto-Configuration
Configured automatically just by adding dependencies
Embedded server
Tomcat built in β runs from a single JAR
Spring Initializr
Generate a project instantly at start.spring.io
Actuator
Health check and metric endpoints out of the box
Creating a project
Here you look at Creating a project alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
In Spring Initializr (start.spring.io) you choose the build tool and dependencies and generate the project skeleton right away. The Gradle Kotlin DSL has configuration autocompletion and type checking, which makes it easier to maintain than the Groovy DSL on large projects.
BASH
# start.spring.io β Gradle Kotlin, Java 21, dependencies:# Spring Web, Spring Data JPA, Spring Security# H2 Database, Lombok, Validation./gradlew bootRun # run./gradlew bootJar # build
Your first REST API
Here you look at Your first REST API alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
@RestController automatically serializes the return value of a method to JSON and puts it in the response body, and @RequestMapping sets the base URL path this controller handles. For list endpoints that need pagination, the single return type Page also delivers metadata such as the page number and total count.
JAVA
@RestController@RequestMapping("/api/v1/users")@RequiredArgsConstructorpublic class UserController { private final UserService userService; @GetMapping public Page<UserResponse> list(@RequestParam(defaultValue="0") int page) { return userService.findAll(PageRequest.of(page, 20)); } @PostMapping @ResponseStatus(HttpStatus.CREATED) public UserResponse create(@Valid @RequestBody CreateUserRequest req) { return userService.create(req); }}
DI / IoC
Here you look at DI / IoC alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
The heart of Spring is the IoC (Inversion of Control) container. Instead of the developer creating objects (beans) directly with `new`, the container builds the needed dependencies ahead of time and injects them where they are needed (DI). Thanks to this, a class only declares "what I will use" and does not have to care "how it gets built".
ConstructorInjection.javaJAVA
// Recommended: constructor injection β final guarantees immutability, and mocks are easy to inject in tests@Service@RequiredArgsConstructor // Lombok generates a constructor taking the final fieldspublic class OrderService { private final PaymentClient paymentClient; private final OrderRepository orderRepository; public Order placeOrder(OrderRequest req) { paymentClient.charge(req.amount()); return orderRepository.save(Order.from(req)); }}// Not recommended: field injection β cannot be final, and mocks cannot be injected in tests without reflection@Servicepublic class LegacyOrderService { @Autowired private PaymentClient paymentClient;}
Injection style
Characteristics
Recommended?
Constructor injection
Allows final fields, makes required dependencies explicit, surfaces circular references early
Recommended
Setter injection
Suits optional dependencies; can be reset at runtime
Use sparingly
Field injection
Short code, but no immutability guarantee and hard to write pure unit tests for
Avoid
Designing a full REST API
Here you look at Designing a full REST API alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
The baseline is a three-layer structure: the Controller handles only the conversion of HTTP requests/responses, and delegates the actual business logic to the Service and data access to the Repository. Each layer should call only the layer directly below it; skipping layers, such as a Controller calling a Repository directly, makes the logic hard to reuse or test later.
Rendering diagramβ¦
HTTP status code
When to use it
200 OK
Successful read or update, with a response body
201 Created
Successful creation β including the URI of the new resource in the Location header is recommended
204 No Content
Success with no response body, such as a successful delete
400 Bad Request
Request validation failed (@Valid failure and so on)
404 Not Found
The requested resource does not exist
409 Conflict
A state conflict such as duplicate creation or an optimistic lock collision
Spring Data JPA
Here you look at Spring Data JPA alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Just by extending JpaRepository you get basic CRUD methods such as save, findById, and delete automatically, and when you name a method according to the rules, like findByEmail, Spring analyzes the name and generates the SQL for you. The key point is that the data access layer is completed by an interface declaration alone, with no separate SQL or implementation.
Here you look at Exception handling alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Instead of repeating try-catch in every controller, catch exceptions from across the application in one place with `@RestControllerAdvice` and convert them into error responses in a consistent format. That way the client always receives an error response of the same shape, whichever API it calls.
GlobalExceptionHandler.javaJAVA
@RestControllerAdvicepublic class GlobalExceptionHandler { @ExceptionHandler(EntityNotFoundException.class) public ResponseEntity<ErrorResponse> handleNotFound(EntityNotFoundException ex) { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body(new ErrorResponse("NOT_FOUND", ex.getMessage())); } @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException ex) { String message = ex.getBindingResult().getFieldErrors().stream() .map(err -> err.getField() + ": " + err.getDefaultMessage()) .collect(Collectors.joining(", ")); return ResponseEntity.badRequest().body(new ErrorResponse("VALIDATION_ERROR", message)); } @ExceptionHandler(Exception.class) public ResponseEntity<ErrorResponse> handleUnexpected(Exception ex) { log.error("Unhandled exception", ex); // always log the stack trace so the cause can be found return ResponseEntity.internalServerError() .body(new ErrorResponse("INTERNAL_ERROR", "A temporary error occurred")); }}record ErrorResponse(String code, String message) {}
Spring Security (JWT)
Here you look at Spring Security (JWT) alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
JWT (JSON Web Token) authentication is a stateless approach in which the server stores no session. At login the server issues a signed token, and from then on the client sends that token in the Authorization header with every request; a filter verifies the signature to determine whose request it is.
Rendering diagramβ¦
SecurityConfig.javaJAVA
@Configuration@EnableWebSecurity@RequiredArgsConstructorpublic class SecurityConfig { private final JwtAuthFilter jwtAuthFilter; @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http .csrf(AbstractHttpConfigurer::disable) // a stateless API needs no CSRF token .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(auth -> auth .requestMatchers("/api/login", "/api/signup").permitAll() .anyRequest().authenticated()) .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class) .build(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }}
Testing (JUnit + MockMvc)
Here you look at Testing (JUnit + MockMvc) alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Unit tests verify Service layer logic quickly by replacing dependencies with fakes through Mockito, and integration tests bring up a real Spring context with `@SpringBootTest` or `@WebMvcTest` and verify from the controller down. Writing the two kinds separately lets you catch logic bugs efficiently with fast unit tests and the API contract (request/response format) with integration tests.
One piece of Service logic (dependencies replaced with Mockito)
Very fast
@ExtendWith(MockitoExtension.class)
Web layer test
Controller + request/response serialization
Fast
@WebMvcTest
Integration test
The full Spring context + a real DB (H2 and so on)
Slow
@SpringBootTest
Docker deployment
Here you look at Docker deployment alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Separating the build stage (JDK) from the runtime stage (JRE) with a multi-stage build leaves no compile tools in the final image, which shrinks the image considerably. Running the dependency download (gradlew dependencies) before copying the source also speeds up builds, because the dependency layer is reused from cache when only the source has changed.
Spring Boot practical design is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.
With Spring Boot, understand the auto-configuration and override only the parts you need, explicitly. Beyond Controller-Service-Repository, transaction boundary and domain event design matter.
Decision point
Question to ask
Practical guideline
Boundaries
Which parts of the Spring Boot code are most likely to change?
Separate input/output, configuration, external integrations, and the core rules.
State
Where is state created and where does it go away?
Make the owner and lifecycle of state visible in the code.
Failure
What does the caller receive on failure?
Decide the timeout, fallback, and error contract first.
Spring Boot operating standards
This section covers Spring Boot operating standards from a practical perspective. Instead of memorizing the concept, focus on the situations in which you would reach for it.
Treat Actuator, Micrometer, profiles, graceful shutdown, and connection pool settings as operational defaults.
Spring Boot verification strategy
Spring Boot verification strategy is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.
Cut back on overusing @SpringBootTest and compose purpose-specific tests from slice tests, contract tests, and Testcontainers.
Quality axis
How to verify
Definition of done
Correctness
Automate the normal/failure cases.
The core scenarios pass reproducibly.
Regression prevention
When fixing a bug, leave the same case behind as a test.
The same failure is not deployed again.
Operability
Check the logs, metrics, and alerts.
There is a path for tracing the cause when a problem occurs.
Spring Boot: frequently asked questions
What is dependency injection (DI) and why use it?
It means an object receives the other objects it needs from outside instead of creating them itself. The Spring container creates the objects (beans) and puts them where they are needed. Swapping implementations or replacing them with fakes in tests becomes easy, and object creation and wiring are managed in one place.
Should I use field injection or constructor injection?
Constructor injection is recommended. The required dependencies are visible in the constructor, fields can be declared final to prevent changes, and the object can be created and tested without Spring. Circular dependencies are also found right at application startup.
I added @Transactional but nothing rolls back. What should I check?
Calling a method directly from within the same class bypasses the proxy, so no transaction is applied. By default only RuntimeException and Error trigger a rollback, so to roll back on a checked exception you need rollbackFor. Catching and swallowing the exception inside the method also prevents the rollback.