All guides
  1. Home
  2. Technical guides
  3. Development

DevelopmentBasic level

Java Spring Boot development best practices

7 min read

All guides

Java Spring Boot development best practices

A guide to day-to-day best practices with Java and Spring Boot: nothing complex, just the decisions that make the biggest difference when a service grows, changes hands or has to be debugged in production. Each practice comes with an example of what to avoid and what to do. The README.md on the left has the checklist for reviewing your code.

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).

Step by step

1. Organise the code by feature

Group by feature (orders, customers…) and not only by technical layer (all controllers together, all services together). Each folder contains what its part of the business needs, and it is easy to find, change or extract something without touching the rest.

src/main/java/com/company/orders/
├── OrdersApplication.java
├── order/
│   ├── OrderController.java
│   ├── OrderService.java
│   ├── OrderRepository.java
│   ├── Order.java               (entity)
│   └── dto/
│       ├── OrderRequest.java
│       └── OrderResponse.java
├── customer/
│   └── ...
└── common/
    ├── error/GlobalExceptionHandler.java
    └── config/...

2. Inject dependencies through the constructor

Instead of this:

@Service
public class OrderService {

    @Autowired
    private OrderRepository repository;   // field injection: hard to test
}

Do this: final fields make it clear what the class needs, it cannot be left half-built and it can be tested without starting Spring.

@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;
    }
}

3. Separate entities from what the API exposes

Don’t return JPA entities from controllers: you expose internal fields, couple the API to the database and can trigger extra queries. Use DTOs; Java record types are perfect for this.

// 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());
    }
}

4. Validate input at the edge

Declare the rules in the DTO (@NotBlank, @NotNull, @PositiveOrZero…) and enable them with @Valid. If the request does not meet them, Spring responds with 400 before it reaches your logic.

@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);
    }
}

5. Centralise error handling

A single @RestControllerAdvice translates exceptions into consistent HTTP responses. Spring Boot 3 includes ProblemDetail, the standard error format (RFC 9457):

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());
    }
}

And so that validation and Spring errors use the same format:

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

6. Take configuration and secrets out of the code

Values that change between environments go in application.yml, and secrets go in environment variables or a secrets manager (Azure Key Vault, Vault…), never in the repository:

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

Group your own configuration in a typed class instead of scattering @Value across the code:

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

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

And use profiles for what changes per environment:

application.yml            common to all environments
application-dev.yml        local development
application-prod.yml       production

java -jar orders.jar --spring.profiles.active=prod

7. Put transactions in the service layer

The service is what knows which operations form a unit. Mark the class as read-only and open write transactions where they are needed:

@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));
    }
}

8. Write useful logs with SLF4J

Instead of this:

System.out.println("Order created: " + order);                  // does not reach the logging system
log.info("Login by " + user + " with password " + password);     // always concatenates and leaks a secret

Do this: messages with {} parameters (they are not built if the level is disabled), the right level (error for failures that require action, info for business events, debug for detail) and never passwords, tokens or personal data.

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

9. Comment the why, not the what

Well-named code already says what it does; the comment explains why: a business rule, an external limitation, a non-obvious decision. Document with Javadoc the public methods that other teams use, and don’t leave commented-out code: that is what git is for.

// 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) { ... }

10. Use clear names and small methods

  • Classes with nouns (OrderService), methods with verbs (createOrder), booleans that read like a question (isPaid).
  • One method, one responsibility: if you need a comment to separate its parts, it is probably several methods.
  • Named constants instead of loose numbers or strings (MAX_BATCH_SIZE instead of 500).
  • Return empty collections, not null; use Optional only as a return type, not in fields or parameters.

11. Test each thing at its level

Many fast unit tests of the logic, and fewer integration tests for what touches Spring or the database.

Business logic: JUnit 5 and Mockito

@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"));
    }
}

Web layer: @WebMvcTest

@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());
    }
}

For repositories, @DataJpaTest, and if you use a real database in your tests, Testcontainers.

12. Expose the service’s health with Actuator

Actuator provides health and metrics endpoints ready for Kubernetes and for monitoring. Expose only the ones you need:

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

13. Automate quality

  • A common format applied automatically (for example, Spotless) so that reviews talk about logic and not whitespace.
  • Static analysis in the IDE (SonarLint) and in the pipeline (SonarQube or SonarCloud) with a quality gate.
  • Automatic dependency updates (Dependabot or Renovate) so vulnerabilities don’t pile up.
  • Tests and analysis mandatory on every pull request before merging.

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.

Share

More guides on

See all guides

Other technical guides

See all guides

APIsIntermediate

Basic structure of an API in IBM API Connect 10

How an API is structured in IBM API Connect 10: OpenAPI contract with x-ibm-configuration, Client ID and Client Secret, product with plans and limits, and validation and publishing with the apic CLI.

Read the guide 7 min read

IntegrationIntermediate

TIBCO ActiveSpaces 5.2: basic administration commands

The day-to-day commands in TIBCO ActiveSpaces 5.2: realm service on FTL servers, tibdg, grid definition, tables, starting processes, status, scaling with copysets, checkpoints and logs.

Read the guide 8 min read

DevOpsBasic

Basic CI/CD structure with GitHub Actions

A complete pipeline with GitHub Actions: tests on every push and pull request, a Docker image in GitHub Container Registry and deployment to a protected environment, with a workflow ready to copy.

Read the guide 6 min read

Contact

Build your next competitive advantage today

Let’s talk about how we can help you. We will reply with a clear technical proposal, with no obligation.

Request information

Fields marked with are required.