---
description: Enforces modern Spring Boot best practices for Java applications, covering code structure, dependency injection, API design, error handling, and testing to ensure maintainable, performant, and secure microservices.
globs: **/*.java
---
# springboot Best Practices
This guide outlines the definitive best practices for developing Spring Boot 3.x applications with Java 17+. Adhere to these rules to build robust, maintainable, and performant services.
## 1. Code Organization and Structure
Organize your codebase by feature or bounded context, not by technical layer. This improves navigability, cohesion, and testability.
❌ BAD: Technical Layering
```
com.myapp.project.controller.UserController
com.myapp.project.service.UserService
com.myapp.project.repository.UserRepository
```
✅ GOOD: Feature-based (Bounded Context)
```java
// Root application class in base package
package com.myapp.project;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProjectApplication {
public static void main(String[] args) {
SpringApplication.run(ProjectApplication.class, args);
}
}
// User feature package
package com.myapp.project.user;
// User feature sub-packages
package com.myapp.project.user.api; // REST controllers, DTOs
package com.myapp.project.user.domain; // Business logic, entities
package com.myapp.project.user.infrastructure; // Repositories, external integrations
```
## 2. Dependency Management
Always inherit from `spring-boot-starter-parent` or use `spring-boot-dependencies` BOM for consistent dependency versions.
✅ GOOD: Maven `pom.xml`
```xml
org.springframework.bootspring-boot-starter-parent3.2.11org.springframework.bootspring-boot-starter-web
```
## 3. Dependency Injection
Prefer constructor injection for all dependencies. This ensures immutability, simplifies testing, and makes dependencies explicit. Use Lombok's `@RequiredArgsConstructor` for conciseness.
❌ BAD: Field Injection
```java
@Service
public class UserService {
@Autowired // Avoid field injection
private UserRepository userRepository;
}
```
✅ GOOD: Constructor Injection with Lombok
```java
package com.myapp.project.user.domain;
import com.myapp.project.user.infrastructure.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor // Automatically generates constructor for final fields
public class UserService {
private final UserRepository userRepository; // Make dependencies final
public User findUserById(Long id) {
return userRepository.findById(id).orElseThrow(() -> new UserNotFoundException(id));
}
}
```
## 4. API Design and Controllers
Controllers must be stateless and focused solely on routing HTTP requests and responses. Delegate all business logic to service layers. Use DTOs for request/response bodies.
❌ BAD: Business Logic in Controller
```java
@RestController
@RequestMapping("/api/users")
public class UserController {
@PostMapping
public ResponseEntity createUser(@RequestBody User user) {
// Business logic directly in controller - BAD
if (user.getEmail() == null || !user.getEmail().contains("@")) {
throw new IllegalArgumentException("Invalid email");
}
// ... more logic
return ResponseEntity.ok(userRepository.save(user));
}
}
```
✅ GOOD: Lean Controller, Delegate to Service
```java
package com.myapp.project.user.api;
import com.myapp.project.user.domain.UserService;
import com.myapp.project.user.api.dto.UserCreateRequest;
import com.myapp.project.user.api.dto.UserResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {
private final UserService userService;
@PostMapping
public ResponseEntity createUser(@RequestBody UserCreateRequest request) {
UserResponse response = userService.createUser(request);
return new ResponseEntity<>(response, HttpStatus.CREATED);
}
@GetMapping("/{id}")
public ResponseEntity getUserById(@PathVariable Long id) {
UserResponse response = userService.findUserById(id);
return ResponseEntity.ok(response);
}
}
```
## 5. Logging
Use SLF4J with Logback (Spring Boot's default) for all logging. Avoid `System.out.print()`. Use Lombok's `@Slf4j` for convenience. Avoid string concatenation in log messages; use parameterized logging.
❌ BAD: `System.out.print()` and String Concatenation
```java
public void process(String data) {
System.out.println("Processing data: " + data); // BAD
log.info("Processing data: " + data); // Still BAD for performance
}
```
✅ GOOD: Parameterized SLF4J Logging
```java
package com.myapp.project.user.domain;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Service
@Slf4j // Provides 'log' field
public class UserService {
public void processData(String data) {
log.info("Processing data: {}", data); // Use placeholders for performance
try {
// ... business logic
} catch (Exception e) {
log.error("Failed to process data: {}", data, e); // Include exception
}
}
}
```
## 6. Error Handling
Implement global exception handling using `@RestControllerAdvice` to provide consistent and meaningful error responses.
✅ GOOD: Global Exception Handler
```java
package com.myapp.project.common.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity