Spring Boot Tutorial

59 posts in this section

Handling Requests: Path Variables, Query Params, and Request Bodies

A REST API receives data in many places: URL path, query string, body, headers, cookies. This article covers every way to extract that data in Spring MVC. @PathVariable — Extract from URL Use @PathVariable when the data is part of the URL path: // URL: GET /api/orders/550e8400-e29b-41d4-a716-446655440000 @GetMapping("/{id}") public OrderResponse getOrder(@PathVariable UUID id) { return orderService.findById(id) .map(OrderResponse::from) .orElseThrow(() -> new OrderNotFoundException(id)); } Spring automatically converts the string segment to the parameter type (UUID, Long, int, etc.

Continue reading »

How Spring Boot Auto-Configuration Works — The Magic Explained

Spring Boot “just works” — you add a dependency and things appear in your application context. This article explains exactly how that happens, so you can debug it when it doesn’t, and extend it when you need to. What Auto-Configuration Actually Does When you add spring-boot-starter-data-jpa to your project, you don’t write a single line of config — yet Spring creates a DataSource, EntityManagerFactory, and JpaTransactionManager automatically. That’s auto-configuration. Auto-configuration is a set of @Configuration classes that Spring Boot ships.

Continue reading »

Integration Testing with @SpringBootTest and Testcontainers

Integration tests verify that all layers work together — HTTP → controller → service → repository → database. This article shows how to write them efficiently with Testcontainers and manage test isolation. @SpringBootTest — The Full Context @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class OrderIntegrationTest { // Loads the FULL Spring ApplicationContext // Everything: controllers, services, repositories, security // Starts on a random port (avoids port conflicts when running tests in parallel) } WebEnvironment options Option What it starts Use for RANDOM_PORT Embedded server on random port Full HTTP round-trip tests DEFINED_PORT Embedded server on configured port When you need a fixed port MOCK (default) No real server, MockMvc available Fast tests without real HTTP NONE No server at all Service/repo tests only Testcontainers — Real Database <dependency> <groupId>org.

Continue reading »

Inter-Service Communication with OpenFeign and RestClient

Services call each other over HTTP. You can use raw RestClient with a URL, or you can use OpenFeign — a declarative HTTP client that turns an interface into a fully functional HTTP client. This article covers both. OpenFeign: Declarative HTTP Client <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> @SpringBootApplication @EnableFeignClients public class OrderServiceApplication { } Defining a Feign Client @FeignClient( name = "inventory-service", // service name — resolved via Eureka path = "/api/inventory" ) public interface InventoryClient { @GetMapping("/products/{productId}/availability") InventoryResponse checkAvailability( @PathVariable UUID productId, @RequestParam int quantity ); @PostMapping("/reservations") ReservationResponse reserve(@RequestBody ReservationRequest request); @DeleteMapping("/reservations/{reservationId}") void cancelReservation(@PathVariable UUID reservationId); @GetMapping("/products") Page<ProductResponse> findProducts( @RequestParam String category, @SpringQueryMap Pageable pageable // Pageable as query params ); } Using it — just inject and call:

Continue reading »

Introduction to Messaging with Apache Kafka

REST APIs are synchronous — the caller waits for a response. Sometimes you don’t want that. An order creation shouldn’t wait for the inventory system, the notification system, and the analytics system to all respond before confirming to the user. Kafka decouples these concerns. What Kafka Is Kafka is a distributed event streaming platform. It stores events (messages) in an ordered, immutable log. Producers write to Kafka; consumers read from it.

Continue reading »

Introduction to Spring Boot — What It Is and Why It Exists

You want to build a Java web application or REST API. You’ve heard everyone uses Spring Boot. But what is it exactly, and why does it exist? This article answers that — clearly — before writing a single line of code. What Is Spring Boot? Spring Boot is an opinionated framework for building Spring-based Java applications with minimal configuration. Break that down: Spring-based — it sits on top of the Spring Framework, which has been the dominant Java application framework since 2003 Minimal configuration — you describe what you want (a web app, a database connection), and Spring Boot figures out how to set it up Opinionated — it makes sensible default choices so you don’t have to make every decision yourself The one-line version: Spring Boot lets you go from a blank project to a running application in minutes, with production-ready defaults built in.

Continue reading »

Introduction to Spring Data JPA

Most Spring Boot applications need to read and write data to a relational database. Spring Data JPA makes this dramatically simpler by generating the boilerplate data access code for you. This article explains what it is, how it fits together, and how to get started. The Stack: JPA, Hibernate, and Spring Data JPA These three things work together — understanding the layering matters: Your Code (Repository interfaces, @Entity classes) │ ▼ Spring Data JPA (generates repository implementations, adds convenience methods) │ ▼ JPA (Jakarta Persistence API) (standard specification: @Entity, @Id, EntityManager, JPQL) │ ▼ Hibernate (JPA implementation) (translates JPA operations to SQL, manages sessions) │ ▼ JDBC (Java Database Connectivity) (sends SQL to the database) │ ▼ PostgreSQL / MySQL / H2 / etc.

Continue reading »

JPA Entity Mapping: @Entity, @Id, @Column, and More

JPA entity mapping defines how Java objects translate to database tables. Get it right and your schema is clean, performant, and expressive. This article covers every mapping annotation you’ll need. @Entity and @Table @Entity @Table( name = "orders", // table name (default: class name) schema = "commerce", // database schema indexes = { @Index(name = "idx_orders_customer_id", columnList = "customer_id"), @Index(name = "idx_orders_status_created", columnList = "status, created_at") }, uniqueConstraints = { @UniqueConstraint(name = "uq_order_number", columnNames = "order_number") } ) public class Order { // .

Continue reading »

JPA Performance: Solving N+1, Lazy Loading, and Query Optimization

JPA makes data access easy — until it silently runs hundreds of queries to load what you think is a single query. This article covers how to find and fix the most common JPA performance problems. Enable Query Logging First You can’t fix what you can’t see. Enable SQL logging before optimizing: logging: level: org.hibernate.SQL: DEBUG org.hibernate.orm.jdbc.bind: TRACE # log bind parameters (Spring Boot 3+) spring: jpa: properties: hibernate: format_sql: true generate_statistics: true # log query count, cache hits, etc.

Continue reading »

JPQL, @Query, and Native Queries in Spring Data JPA

Derived query methods cover simple cases. Complex filtering, aggregation, and reporting queries need JPQL or native SQL. This article covers both with practical examples. JPQL vs SQL vs Native SQL JPQL Native SQL Writes Entity-oriented (FROM Order o) Table-oriented (FROM orders o) Portability DB-agnostic DB-specific Features Basic SQL + JPA joins Full DB-specific SQL (CTEs, window functions, JSONB) Type-safety Partial None Use for Most queries Reporting, DB-specific features @Query with JPQL public interface OrderRepository extends JpaRepository<Order, UUID> { // Basic JPQL — uses entity/field names, not table/column names @Query("SELECT o FROM Order o WHERE o.

Continue reading »