Skip to main content
AIDevOps
  • Learn
  • Learning Paths
  • Practice
  • Open Source
  • Books
  • Engineering

    AI DevOpsThe full map of building and operating AI servicesLLMOpsLLM deployment Β· evaluation Β· observabilityHands-on ProjectsBuild AI Agent projects

    Knowledge

    DocsTechnical documentationBlogEngineering articlesPloggerDevelopment log feed

    Validate

    Certification3-level skills certification Β· coming soon
AI Models
LlamaTutorial|MistralTutorial|GemmaTutorial|DeepSeekTutorial|QwenTutorial
🌱 Spring Cloud
Spring Intro & RoadmapSpring Cloud GatewaySpring BootJava|Spring AISpring SecuritySpring BatchSpring JPA
πŸ€– AI Applied Development
Applied AI Intro & RoadmapHugging FaceLangChainLlamaIndexLLMOps|LangGraphMCPMulti-AgentAgent Evaluation
🧠 AI Core
AI Intro & RoadmapML FundamentalsLLM Fundamentals|Python AIC++|PyTorchTensorFlowJAX
🧠 AI Agent Development
Finance AI AgentLLM API ServerStock Investing AgentAIOps AI AgentEducation AI AgentCoding AI Agent
🐳 DevOps
DevOps Intro & RoadmapLinuxDockerCI/CD|Kubernetes BasicsK8s AdvancedPrometheusGrafana
🧱 Infrastructure
Infrastructure Intro & RoadmapNginxRedis
☁️ Cloud
Cloud Intro & RoadmapAWSGCPAzureNCPCloudflare
🎨 Frontend
Frontend Intro & RoadmapJavaScriptTypeScript|ReactNext.js|VueNuxt|Electron
πŸ“± Mobile
Mobile Intro & RoadmapKotlinAndroidFlutter
βš™οΈ Backend
Backend Intro & RoadmapPython BasicsFastAPIDjangoFlask|CGoGinNode.js
πŸ’Ύ Database
DB Intro & RoadmapCore SQLOracleMySQLPostgreSQL|MongoDBVector DB
πŸ§ͺ Testing
k6JMeternGrinder
AIDevOps

Engineering AI. From Code to Production.
An engineering learning platform for building and operating AI and AI Agents

Learn

  • All Guides
  • Learning Paths
  • AI Tutorial
  • Practice
  • Books

Resources

  • AI DevOps
  • LLMOps
  • Hands-on Projects
  • Docs
  • Blog
  • Plogger
  • Open Source
  • Certification (coming soon)

Start Here

  • AI Core Roadmap
  • AI Applied Development Roadmap
  • Spring Cloud Roadmap
  • DevOps Roadmap
  • Infrastructure Roadmap

Β 

  • Cloud Roadmap
  • Frontend Roadmap
  • Mobile Roadmap
  • Backend Roadmap
  • Database Roadmap
Β© 2026 AIDevOps. All rights reserved.
Terms of ServicePrivacy PolicySitemaptestforge.kr
  1. Home
  2. Learn
  3. Spring Cloud
  4. Spring Boot
Guide to the Java framework

πŸƒ Spring Boot Complete Guide

Visitors

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.

Open the Web IDE β†’
REST API serversJPA/Hibernate ORMSpring Security JWTMSA backends

Related frameworks & environments

β˜•Javaβ†’GWSpring Cloud Gatewayβ†’πŸ”Spring Securityβ†’πŸ—„οΈSpring JPAβ†’βš™οΈSpring Batchβ†’

Contents

0 / 16
  1. How to use this guide
  2. Architecture diagrams
  3. What is Spring Boot?
  4. Creating a project
  5. Your first REST API
  6. DI / IoC
  7. Designing a full REST API
  8. Spring Data JPA
  9. Exception handling
  10. Spring Security (JWT)
  11. Testing (JUnit + MockMvc)
  12. Docker deployment
  13. Spring Boot design
  14. Operating standards
  15. Verification strategy
  16. Frequently asked questions
Contents 16 sections
  1. How to use this guide
  2. Architecture diagrams
  3. What is Spring Boot?
  4. Creating a project
  5. Your first REST API
  6. DI / IoC
  7. Designing a full REST API
  8. Spring Data JPA
  9. Exception handling
  10. Spring Security (JWT)
  11. Testing (JUnit + MockMvc)
  12. Docker deployment
  13. Spring Boot design
  14. Operating standards
  15. Verification strategy
  16. Frequently asked questions

How to use this guide

How to read it

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.
FeatureDescription
Auto-ConfigurationConfigured automatically just by adding dependencies
Embedded serverTomcat built in β€” runs from a single JAR
Spring InitializrGenerate a project instantly at start.spring.io
ActuatorHealth 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")
@RequiredArgsConstructor
public 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 fields
public 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
@Service
public class LegacyOrderService {
    @Autowired
    private PaymentClient paymentClient;
}
Injection styleCharacteristicsRecommended?
Constructor injectionAllows final fields, makes required dependencies explicit, surfaces circular references earlyRecommended
Setter injectionSuits optional dependencies; can be reset at runtimeUse sparingly
Field injectionShort code, but no immutability guarantee and hard to write pure unit tests forAvoid

Tip

Rather than putting @Autowired directly on fields, make constructor injection + @RequiredArgsConstructor from Lombok your default β€” the Spring team officially recommends constructor injection too.

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 codeWhen to use it
200 OKSuccessful read or update, with a response body
201 CreatedSuccessful creation β€” including the URI of the new resource in the Location header is recommended
204 No ContentSuccess with no response body, such as a successful delete
400 Bad RequestRequest validation failed (@Valid failure and so on)
404 Not FoundThe requested resource does not exist
409 ConflictA state conflict such as duplicate creation or an optimistic lock collision

Tip

Do not return an Entity directly in the response; convert it to a separate Response DTO β€” the associations of the Entity (lazy loading) get serialized to JSON as they are, which easily leads to unwanted queries or circular reference errors.

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.
JAVA
@Entity @Table(name="users")
@Getter @Builder @NoArgsConstructor @AllArgsConstructor
public class User {
    @Id @GeneratedValue(strategy=IDENTITY) private Long id;
    @Column(nullable=false)               private String name;
    @Column(nullable=false, unique=true)  private String email;
    @CreationTimestamp private LocalDateTime createdAt;
}

public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByEmail(String email);
    boolean existsByEmail(String email);
}

Exception handling

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
@RestControllerAdvice
public 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) {}

Tip

In the final handler that catches Exception.class, do not expose the original exception message to the client as-is β€” internal implementation details (SQL, class names, and so on) can leak. Log the stack trace on the server instead, and return only a generic message to the client.

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
@RequiredArgsConstructor
public 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();
    }
}

Tip

  • Once a JWT is issued the server does not separately remember that it exists, so logout and forced invalidation are trickier than with sessions β€” consider a short expiry + Refresh Token combination, or a blocklist as well.
  • Storing the token in an httpOnly cookie is safer against XSS attacks than keeping it in the localStorage of the browser.

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.
OrderControllerTest.javaJAVA
@WebMvcTest(OrderController.class)
class OrderControllerTest {
    @Autowired MockMvc mockMvc;
    @MockBean OrderService orderService;

    @Test
    void createOrder_succeeds() throws Exception {
        given(orderService.placeOrder(any())).willReturn(new Order(1L, 10000));

        mockMvc.perform(post("/api/v1/orders")
                .contentType(MediaType.APPLICATION_JSON)
                .content("""
                    {"productId": 1, "amount": 10000}
                """))
            .andExpect(status().isCreated())
            .andExpect(jsonPath("$.id").value(1));
    }

    @Test
    void validationFailure_returns400() throws Exception {
        mockMvc.perform(post("/api/v1/orders")
                .contentType(MediaType.APPLICATION_JSON)
                .content("{}"))
            .andExpect(status().isBadRequest());
    }
}
Test typeScopeSpeedTypical annotation
Unit testOne piece of Service logic (dependencies replaced with Mockito)Very fast@ExtendWith(MockitoExtension.class)
Web layer testController + request/response serializationFast@WebMvcTest
Integration testThe full Spring context + a real DB (H2 and so on)Slow@SpringBootTest

Tip

Writing every test with @SpringBootTest alone makes the whole test suite slow, because the Spring context is started anew each time β€” keep run time in check by verifying logic with unit tests and narrowing integration tests to checking how the layers work together.

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.
DOCKERFILE
FROM eclipse-temurin:21-jdk-alpine AS builder
WORKDIR /app
COPY gradlew build.gradle.kts settings.gradle.kts ./
COPY gradle ./gradle
RUN ./gradlew dependencies --no-daemon
COPY src ./src
RUN ./gradlew bootJar --no-daemon

FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
COPY --from=builder /app/build/libs/*.jar app.jar
USER nobody
EXPOSE 8080
ENTRYPOINT ["java","-jar","app.jar"]

Tip

Running the application inside the container as a non-root account with USER nobody makes it hard for an attacker to gain privileges that could affect the host even if the container is compromised.

Spring Boot practical design

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 pointQuestion to askPractical guideline
BoundariesWhich parts of the Spring Boot code are most likely to change?Separate input/output, configuration, external integrations, and the core rules.
StateWhere is state created and where does it go away?Make the owner and lifecycle of state visible in the code.
FailureWhat 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.

Tip

  • transaction boundary
  • Actuator health
  • profile config
  • slice tests

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 axisHow to verifyDefinition of done
CorrectnessAutomate the normal/failure cases.The core scenarios pass reproducibly.
Regression preventionWhen fixing a bug, leave the same case behind as a test.The same failure is not deployed again.
OperabilityCheck 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.

← Previous guideSpring Cloud GatewayNext guide β†’Java