Build Production-Grade
Java Applications
A comprehensive guide taking you from "Hello World" to a Dockerized, database-backed API with proper validation and testing.
Part 1: The Basics
Why Spring Boot?
- Opinionated: Auto-configuration reduces setup time by 90%.
- Standalone: Embedded Tomcat server means no WAR deployment.
- Production Ready: Metrics and health checks built-in.
Key Annotations
@SpringBootApplication
Triggers auto-configuration and component scanning.
@RestController
Marks a class as a web handler returning JSON.
Your First Controller
package com.example.demo; import org.springframework.web.bind.annotation.*; @RestController public class HelloController { @GetMapping("/hello") public String sayHello() { return "Hello, Spring Boot!"; } }
Part 2: Database & JPA
The 3-Layer Architecture
Controller
HTTP Requests
Service
Business Logic
Repository
Data Access
1. The Entity
@Entity public class Product { @Id @GeneratedValue private Long id; private String name; private Double price; // getters & setters }
2. The Repository
public interface ProductRepository extends JpaRepository<Product, Long> { // Magic method generation List<Product> findByPriceLessThan(Double p); }
Part 3: Validation & DTOs
The Security Risk
Exposing your Database Entities directly to the API is dangerous. Users could send massive payloads or overwrite protected fields. Always use Data Transfer Objects (DTOs).
Request DTO with Validation
public class ProductRequestDTO { @NotBlank(message = "Name required") private String name; @NotNull @Min(value = 0) private Double price; }
Global Exception Handling
Intercepts errors to return clean JSON instead of stack traces.
@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Map> handleErrors(Exception ex) { // Return pretty JSON error map return ResponseEntity.badRequest().body(errors); } }
Part 4: Testing Strategy
Test single classes in isolation. Fast & numerous.
Test interaction between Controller & DB.
Full browser simulation. Slowest.
Unit Test with Mockito
@ExtendWith(MockitoExtension.class) class ProductServiceTest { @Mock private ProductRepository repo; @InjectMocks private ProductService service; @Test void shouldSave() { Product p = new Product("Laptop"); given(repo.save(p)).willReturn(p); // Train mock service.create(p); verify(repo).save(p); // Verify interaction } }
Part 5: Deployment
The Executable JAR
Spring Boot builds a single "Uber JAR" containing your code + dependencies + embedded Tomcat.
Dockerize It
Ensure it runs everywhere by packaging the OS and Java runtime.
# Dockerfile
FROM eclipse-temurin:17-jdk-alpine
COPY target/*.jar app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]