# Java Spring Boot development best practices

A Bitflow Solutions guide. Web version: https://bitflow-solutions.com/en/guias-tecnicas/java-spring-boot-best-practices/

## What you’ll learn

- How to organise a service’s code so it can grow without getting tangled.
- The core practices: constructor injection, DTOs, validation and centralised error handling.
- How to take configuration and secrets out of the code with profiles and environment variables.
- Where to put transactions, how to write useful logs and how to comment code.
- What to test at each level and how to automate quality.

## Prerequisites

- **Java 17 or later** (required by Spring Boot 3).
- A **Spring Boot 3** project, for example generated at `start.spring.io` with Spring Web, Validation, Spring Data JPA and Actuator.
- Maven or Gradle, and an IDE such as IntelliJ IDEA or Visual Studio Code with the Extension Pack for Java.
- Basic knowledge of Java and Spring (controllers, services and repositories).

## Checklist

- [ ] Code organised by feature
- [ ] Dependencies injected through the constructor, final fields
- [ ] DTOs (records) in the API; never JPA entities
- [ ] Input validated with @Valid and Jakarta Validation annotations
- [ ] Errors centralised in @RestControllerAdvice with ProblemDetail
- [ ] Configuration in application.yml and @ConfigurationProperties; secrets in environment variables
- [ ] Profiles per environment (dev, prod)
- [ ] @Transactional in the service, readOnly by default
- [ ] Logs with SLF4J and {} parameters, with no secrets or personal data
- [ ] Comments that explain why; Javadoc on public methods; no commented-out code
- [ ] Clear names, small methods, named constants
- [ ] Unit tests (JUnit 5 + Mockito), @WebMvcTest, @DataJpaTest
- [ ] Actuator with only the endpoints you need
- [ ] Formatting, static analysis and dependency updates automated
- [ ] spring.jpa.open-in-view=false

## Step by step: examples

### Constructor injection

```java
@Service
public class OrderService {

    private final OrderRepository repository;

    // With a single constructor, Spring uses it without needing @Autowired
    public OrderService(OrderRepository repository) {
        this.repository = repository;
    }
}
```

### DTOs with records and validation

```java
// What comes into the API
public record OrderRequest(
        @NotBlank String customer,
        @NotNull @PositiveOrZero BigDecimal amount) {
}

// What leaves the API: only the fields the consumer needs
public record OrderResponse(String id, String customer, BigDecimal amount, String status) {

    static OrderResponse from(Order order) {
        return new OrderResponse(order.getId(), order.getCustomer(),
                order.getAmount(), order.getStatus().name());
    }
}
```

```java
@RestController
@RequestMapping("/api/v1/orders")
public class OrderController {

    private final OrderService service;

    public OrderController(OrderService service) {
        this.service = service;
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public OrderResponse create(@Valid @RequestBody OrderRequest request) {
        return service.create(request);
    }

    @GetMapping("/{id}")
    public OrderResponse read(@PathVariable String id) {
        return service.read(id);
    }
}
```

### Errors with ProblemDetail

```java
public class OrderNotFoundException extends RuntimeException {
    public OrderNotFoundException(String id) {
        super("Order " + id + " does not exist");
    }
}

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(OrderNotFoundException.class)
    ProblemDetail notFound(OrderNotFoundException ex) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
    }
}
```

```yaml
spring:
  mvc:
    problemdetails:
      enabled: true   # validation and Spring errors also in RFC 9457 format
```

### Configuration and secrets

```yaml
spring:
  datasource:
    url: ${DB_URL}
    username: ${DB_USER}
    password: ${DB_PASSWORD}     # never the real value in the repository
  jpa:
    open-in-view: false

orders:
  max-amount: 10000
  retries: 3
```

```java
@ConfigurationProperties(prefix = "orders")
public record OrdersProperties(BigDecimal maxAmount, int retries) {
}

// In the main class (or in a @Configuration)
@SpringBootApplication
@ConfigurationPropertiesScan
public class OrdersApplication { ... }
```

### Transactions in the service

```java
@Service
@Transactional(readOnly = true)          // read-only by default
public class OrderService {

    @Transactional                        // writes, in their own transaction
    public OrderResponse create(OrderRequest request) {
        Order order = repository.save(Order.newOrder(request.customer(), request.amount()));
        return OrderResponse.from(order);
    }

    public OrderResponse read(String id) {
        return repository.findById(id)
                .map(OrderResponse::from)
                .orElseThrow(() -> new OrderNotFoundException(id));
    }
}
```

### Logs

```java
private static final Logger log = LoggerFactory.getLogger(OrderService.class);

log.info("Order {} created for customer {}", order.getId(), order.getCustomer());
log.debug("Details of order {}: {}", order.getId(), order);
log.error("Could not notify order {}", order.getId(), ex);   // the exception goes last
```

### Comments

```java
// Bad: repeats what the code already says
// add 1 to the counter
counter++;

// Good: explains why
// The supplier rejects batches of more than 500 lines (contract v2, clause 4)
private static final int MAX_BATCH_SIZE = 500;

/**
 * Calculates the amount of an order including taxes.
 *
 * @param order order with its lines; cannot be null
 * @return total amount, rounded to two decimal places
 * @throws OrderNotFoundException if the order no longer exists
 */
public BigDecimal amountWithTaxes(Order order) { ... }
```

### Tests

```java
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {

    @Mock OrderRepository repository;
    @InjectMocks OrderService service;

    @Test
    void throwsExceptionIfOrderDoesNotExist() {
        when(repository.findById("X")).thenReturn(Optional.empty());

        assertThrows(OrderNotFoundException.class, () -> service.read("X"));
    }
}
```

```java
@WebMvcTest(OrderController.class)
class OrderControllerTest {

    @Autowired MockMvc mvc;
    @MockitoBean OrderService service;   // @MockBean in versions earlier than Spring Boot 3.4

    @Test
    void rejectsAnOrderWithoutCustomer() throws Exception {
        mvc.perform(post("/api/v1/orders")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("{\"amount\": 10}"))
                .andExpect(status().isBadRequest());
    }
}
```

### Actuator

```yaml
management:
  endpoints:
    web:
      exposure:
        include: health,info,prometheus   # only what is needed
  endpoint:
    health:
      probes:
        enabled: true                     # /actuator/health/liveness and /readiness for Kubernetes
```

## Common errors

- **Field injection with @Autowired**: It works, but it hides dependencies, prevents `final` fields and forces you to use Spring or reflection to test. Move it to the constructor (step 2).
- **Returning JPA entities from the API**: It exposes internal fields and can trigger lazy loading of relationships during serialisation (or fail with `LazyInitializationException`). Use DTOs (step 3).
- **@Transactional that does nothing**: Spring applies transactions through a proxy: they do not work on `private` methods or when a method calls another one in the **same** class. Put it on public methods called from outside.
- **N+1 queries**: Iterating over a list of entities and accessing a lazy relationship fires one query per element. Use `JOIN FETCH` or `@EntityGraph` in the repository, and disable `spring.jpa.open-in-view` to catch it early.
- **Catching Exception and carrying on as if nothing happened**: An empty `catch (Exception e) {}` hides the failure and turns it into incorrect data further down the line. Catch what you know how to handle and let the rest bubble up to the global handler (step 5).
- **Secrets in application.yml**: A password pushed to git stays in the history even if it is deleted later. Use environment variables or a secrets manager, and if one was pushed, change it.
- **System.out.println instead of logs**: It has no levels, does not reach the environment’s logging system and cannot be filtered. Use SLF4J (step 8).

## Next steps

- Document the API with springdoc-openapi and review its contract (see the OpenAPI 3 contract with OAuth and API Key guide).
- Build the container image without a Dockerfile with `./mvnw spring-boot:build-image`.
- Set up the testing, analysis and deployment pipeline (see the CI/CD with GitHub Actions guide).
- Add metrics with Micrometer and Prometheus, and distributed tracing with OpenTelemetry.
