Spring Boot: Enterprise Java Application Framework and Best Practices
Spring Boot Auto-Configuration and Starter Dependencies
Spring Boot philosophy: convention over configuration. @SpringBootApplication auto-configures beans. Starters: spring-boot-starter-web (includes Tomcat, Spring MVC, Jackson). Gradle/Maven: gradle dependency (spring-boot-starter-data-jpa, spring-boot-starter-security). Auto-configuration: Spring detects classpath, configures beans automatically. Example: if H2 database on classpath, configures in-memory database. Disable: @SpringBootApplication(exclude = DataSourceAutoConfiguration.class). Application properties: application.properties or application.yml. server.port=8080, spring.datasource.url=jdbc:mysql://localhost/mydb. Profiles: application-dev.properties, application-prod.properties (environment-specific). Performance: boot application starts ~2-5 seconds (reasonable for JVM). JVM warmup: first requests slightly slower (JIT compiling). Later requests fast (compiled, optimized).
Spring MVC and REST APIs
Controller: @RestController routes HTTP requests. @GetMapping("/users/{id}") public User getUser(@PathVariable int id) { return userService.get(id); }. Path variables: /users/123 → id=123. Query parameters: /users?name=John → @RequestParam. Request body: @PostMapping @RequestBody User newUser (parse JSON). Response: @ResponseEntity
Spring Data and Database Abstraction
Spring Data JPA: repository pattern. interface UserRepository extends JpaRepository
Spring Security and Authentication
Authentication: verify user identity (username/password, OAuth2, JWT). Authorization: verify permissions (role-based, permission-based). Filter chain: security filters intercept requests. Example: request → authentication filter → authorization filter → controller. User password: BCrypt hashing (slow, intentional, <1ms attack unfeasible). Custom user service: UserDetailsService.loadUserByUsername(). JWT tokens: generate on login, include in requests (Authorization header). Token validation: verify signature, check expiration. Refresh tokens: issue new access token after expiration (extends session). OAuth2: delegate authentication (Google, Microsoft). Social login: user approves scope (email, profile), app receives access token. CORS: Cross-Origin Resource Sharing (allow requests from other domains). SSL/TLS: HTTPS enforcement (server.ssl.enabled=true). Security headers: CSP (Content Security Policy), X-Frame-Options (clickjacking protection).
Microservices Architecture with Spring Cloud
Service discovery: Eureka (Netflix). Services register on startup, clients lookup dynamically. Example: payment-service registers at localhost:8761, order-service discovers without hardcoded URL. Load balancing: Ribbon (client-side), Eureka distributes traffic. Circuit breaker: Hystrix/Resilience4j. If service fails (timeout, 503), circuit opens (fail fast, don't keep retrying). Timeout: 5 seconds default, configurable. Fallback: return cached result if service unavailable. Distributed tracing: Spring Cloud Sleuth + Zipkin. Trace ID added to logs (correlate across services). Example: user request → order service → payment service → notification service (trace ID: abc123 throughout). Configuration management: Spring Cloud Config. Centralized configuration (Git repository), services pull on startup. Refresh: ConfigClient refresh (some configs can reload without restart). Message queue: RabbitMQ, Kafka for async communication. Example: order service publishes "OrderCreated" event, email service consumes and sends email (decoupled).
Reactive Programming with Project Reactor
Traditional: blocking I/O (thread sleeps during network call). Reactive: non-blocking, asynchronous. Mono: single value (0 or 1 result). Flux: stream of values (multiple results). Example: Mono.just("Hello") → subscriber receives "Hello" once. Flux.range(1, 5) → subscriber receives 1, 2, 3, 4, 5 sequentially. Operators: map, filter, flatMap, zip (transform/combine streams). Backpressure: subscriber tells publisher slow down (rate limiting). Performance: thousands of concurrent connections on single thread (vs thread-per-connection blocking model). Spring WebFlux: reactive web framework. @GetMapping("/users/{id}") public Mono
Deployment and Operations
Containerization: Docker. Dockerfile: FROM openjdk:17, COPY target/app.jar app.jar, CMD ["java", "-jar", "app.jar"]. Build: mvn clean package (create JAR), docker build -t myapp . (create image). Size: typical app ~300MB (Java runtime + dependencies). Kubernetes: deployment.yaml specifies replicas, liveness probe, readiness probe. Monitoring: Micrometer (metrics), Prometheus (scrapes metrics), Grafana (visualization). Health checks: /actuator/health endpoint (Kubernetes probe). Graceful shutdown: wait for in-flight requests to complete, then stop. Observability: structured logging (Logback configuration), distributed tracing (Sleuth + Zipkin), metrics (Prometheus). Log levels: INFO (normal), DEBUG (development), WARN (attention), ERROR (problems). Performance tuning: GC optimization (G1GC, ZGC), heap size sizing (-Xmx1024m), JVM flags for production. Profiling: JFR (Java Flight Recorder), JProfiler (identify bottlenecks). Deployment: Blue-green (two production environments), Canary (gradual rollout).
Testing and Best Practices
Testing frameworks: JUnit 5 (latest), TestNG (alternative). @Test annotation marks test. Assertions: assertEquals, assertTrue, assertThrows. Mocking: Mockito. mock(UserService.class) creates mock. when(userService.get(1)).thenReturn(new User()). Integration testing: @SpringBootTest (loads full context). @WebMvcTest (only controller layer). Performance: integration tests ~100ms, unit tests ~1ms. Code coverage: JaCoCo (target 70%+). Sonarqube: static code analysis (code smells, bugs, security issues). Design patterns: Singleton (beans), Factory (object creation), Strategy (interchangeable algorithms), Repository (data access). SOLID principles: code structured, testable, maintainable. Architecture: Hexagonal (ports and adapters), Clean Architecture (independent layers). Dependency injection: loose coupling (prefer interfaces over implementations). Configuration management: 12-factor app principles (config in environment, secrets in vault).