{"id":5172,"date":"2026-11-18T21:20:17","date_gmt":"2026-11-18T21:20:17","guid":{"rendered":"https:\/\/bitflow-solutions.com\/guias-tecnicas\/java-spring-boot-best-practices\/"},"modified":"2026-11-18T21:20:17","modified_gmt":"2026-11-18T21:20:17","slug":"java-spring-boot-best-practices","status":"publish","type":"bf_guia","link":"https:\/\/bitflow-solutions.com\/en\/guias-tecnicas\/java-spring-boot-best-practices\/","title":{"rendered":"Java Spring Boot development best practices"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">A guide to day-to-day <strong>best practices<\/strong> with <strong>Java and Spring Boot<\/strong>: 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 <strong>README.md<\/strong> on the left has the checklist for reviewing your code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What you\u2019ll learn<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>How to organise a service\u2019s code so it can grow without getting tangled.<\/li>\n\n\n<li>The core practices: constructor injection, DTOs, validation and centralised error handling.<\/li>\n\n\n<li>How to take configuration and secrets out of the code with profiles and environment variables.<\/li>\n\n\n<li>Where to put transactions, how to write useful logs and how to comment code.<\/li>\n\n\n<li>What to test at each level and how to automate quality.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Java 17 or later<\/strong> (required by Spring Boot 3).<\/li>\n\n\n<li>A <strong>Spring Boot 3<\/strong> project, for example generated at <code>start.spring.io<\/code> with Spring Web, Validation, Spring Data JPA and Actuator.<\/li>\n\n\n<li>Maven or Gradle, and an IDE such as IntelliJ IDEA or Visual Studio Code with the Extension Pack for Java.<\/li>\n\n\n<li>Basic knowledge of Java and Spring (controllers, services and repositories).<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Step by step<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">1. Organise the code by feature<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Group by <strong>feature<\/strong> (orders, customers\u2026) 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.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>src\/main\/java\/com\/company\/orders\/\n\u251c\u2500\u2500 OrdersApplication.java\n\u251c\u2500\u2500 order\/\n\u2502   \u251c\u2500\u2500 OrderController.java\n\u2502   \u251c\u2500\u2500 OrderService.java\n\u2502   \u251c\u2500\u2500 OrderRepository.java\n\u2502   \u251c\u2500\u2500 Order.java               (entity)\n\u2502   \u2514\u2500\u2500 dto\/\n\u2502       \u251c\u2500\u2500 OrderRequest.java\n\u2502       \u2514\u2500\u2500 OrderResponse.java\n\u251c\u2500\u2500 customer\/\n\u2502   \u2514\u2500\u2500 ...\n\u2514\u2500\u2500 common\/\n    \u251c\u2500\u2500 error\/GlobalExceptionHandler.java\n    \u2514\u2500\u2500 config\/...<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">2. Inject dependencies through the constructor<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Instead of this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Service\npublic class OrderService {\n\n    @Autowired\n    private OrderRepository repository;   \/\/ field injection: hard to test\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Do this: <code>final<\/code> fields make it clear what the class needs, it cannot be left half-built and it can be tested without starting Spring.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Service\npublic class OrderService {\n\n    private final OrderRepository repository;\n\n    \/\/ With a single constructor, Spring uses it without needing @Autowired\n    public OrderService(OrderRepository repository) {\n        this.repository = repository;\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">3. Separate entities from what the API exposes<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Don\u2019t return JPA entities from controllers: you expose internal fields, couple the API to the database and can trigger extra queries. Use <strong>DTOs<\/strong>; Java <code>record<\/code> types are perfect for this.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ What comes into the API\npublic record OrderRequest(\n        @NotBlank String customer,\n        @NotNull @PositiveOrZero BigDecimal amount) {\n}\n\n\/\/ What leaves the API: only the fields the consumer needs\npublic record OrderResponse(String id, String customer, BigDecimal amount, String status) {\n\n    static OrderResponse from(Order order) {\n        return new OrderResponse(order.getId(), order.getCustomer(),\n                order.getAmount(), order.getStatus().name());\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">4. Validate input at the edge<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Declare the rules in the DTO (<code>@NotBlank<\/code>, <code>@NotNull<\/code>, <code>@PositiveOrZero<\/code>\u2026) and enable them with <code>@Valid<\/code>. If the request does not meet them, Spring responds with 400 before it reaches your logic.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@RestController\n@RequestMapping(\"\/api\/v1\/orders\")\npublic class OrderController {\n\n    private final OrderService service;\n\n    public OrderController(OrderService service) {\n        this.service = service;\n    }\n\n    @PostMapping\n    @ResponseStatus(HttpStatus.CREATED)\n    public OrderResponse create(@Valid @RequestBody OrderRequest request) {\n        return service.create(request);\n    }\n\n    @GetMapping(\"\/{id}\")\n    public OrderResponse read(@PathVariable String id) {\n        return service.read(id);\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">5. Centralise error handling<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A single <code>@RestControllerAdvice<\/code> translates exceptions into consistent HTTP responses. Spring Boot 3 includes <code>ProblemDetail<\/code>, the standard error format (RFC 9457):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class OrderNotFoundException extends RuntimeException {\n    public OrderNotFoundException(String id) {\n        super(\"Order \" + id + \" does not exist\");\n    }\n}\n\n@RestControllerAdvice\npublic class GlobalExceptionHandler {\n\n    @ExceptionHandler(OrderNotFoundException.class)\n    ProblemDetail notFound(OrderNotFoundException ex) {\n        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">And so that validation and Spring errors use the same format:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>spring:\n  mvc:\n    problemdetails:\n      enabled: true   # validation and Spring errors also in RFC 9457 format<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">6. Take configuration and secrets out of the code<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Values that change between environments go in <code>application.yml<\/code>, and secrets go in environment variables or a secrets manager (Azure Key Vault, Vault\u2026), never in the repository:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>spring:\n  datasource:\n    url: ${DB_URL}\n    username: ${DB_USER}\n    password: ${DB_PASSWORD}     # never the real value in the repository\n  jpa:\n    open-in-view: false\n\norders:\n  max-amount: 10000\n  retries: 3<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Group your own configuration in a typed class instead of scattering <code>@Value<\/code> across the code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@ConfigurationProperties(prefix = \"orders\")\npublic record OrdersProperties(BigDecimal maxAmount, int retries) {\n}\n\n\/\/ In the main class (or in a @Configuration)\n@SpringBootApplication\n@ConfigurationPropertiesScan\npublic class OrdersApplication { ... }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">And use profiles for what changes per environment:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>application.yml            common to all environments\napplication-dev.yml        local development\napplication-prod.yml       production\n\njava -jar orders.jar --spring.profiles.active=prod<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">7. Put transactions in the service layer<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The service is what knows which operations form a unit. Mark the class as read-only and open write transactions where they are needed:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Service\n@Transactional(readOnly = true)          \/\/ read-only by default\npublic class OrderService {\n\n    @Transactional                        \/\/ writes, in their own transaction\n    public OrderResponse create(OrderRequest request) {\n        Order order = repository.save(Order.newOrder(request.customer(), request.amount()));\n        return OrderResponse.from(order);\n    }\n\n    public OrderResponse read(String id) {\n        return repository.findById(id)\n                .map(OrderResponse::from)\n                .orElseThrow(() -&gt; new OrderNotFoundException(id));\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">8. Write useful logs with SLF4J<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Instead of this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>System.out.println(\"Order created: \" + order);                  \/\/ does not reach the logging system\nlog.info(\"Login by \" + user + \" with password \" + password);     \/\/ always concatenates and leaks a secret<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Do this: messages with <code>{}<\/code> parameters (they are not built if the level is disabled), the right level (<code>error<\/code> for failures that require action, <code>info<\/code> for business events, <code>debug<\/code> for detail) and never passwords, tokens or personal data.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>private static final Logger log = LoggerFactory.getLogger(OrderService.class);\n\nlog.info(\"Order {} created for customer {}\", order.getId(), order.getCustomer());\nlog.debug(\"Details of order {}: {}\", order.getId(), order);\nlog.error(\"Could not notify order {}\", order.getId(), ex);   \/\/ the exception goes last<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">9. Comment the why, not the what<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Well-named code already says what it does; the comment explains <strong>why<\/strong>: a business rule, an external limitation, a non-obvious decision. Document with Javadoc the public methods that other teams use, and don\u2019t leave commented-out code: that is what git is for.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Bad: repeats what the code already says\n\/\/ add 1 to the counter\ncounter++;\n\n\/\/ Good: explains why\n\/\/ The supplier rejects batches of more than 500 lines (contract v2, clause 4)\nprivate static final int MAX_BATCH_SIZE = 500;\n\n\/**\n * Calculates the amount of an order including taxes.\n *\n * @param order order with its lines; cannot be null\n * @return total amount, rounded to two decimal places\n * @throws OrderNotFoundException if the order no longer exists\n *\/\npublic BigDecimal amountWithTaxes(Order order) { ... }<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">10. Use clear names and small methods<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Classes with nouns (<code>OrderService<\/code>), methods with verbs (<code>createOrder<\/code>), booleans that read like a question (<code>isPaid<\/code>).<\/li>\n\n\n<li>One method, one responsibility: if you need a comment to separate its parts, it is probably several methods.<\/li>\n\n\n<li>Named constants instead of loose numbers or strings (<code>MAX_BATCH_SIZE<\/code> instead of <code>500<\/code>).<\/li>\n\n\n<li>Return empty collections, not <code>null<\/code>; use <code>Optional<\/code> only as a return type, not in fields or parameters.<\/li>\n\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">11. Test each thing at its level<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Many fast unit tests of the logic, and fewer integration tests for what touches Spring or the database.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Business logic: JUnit 5 and Mockito<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>@ExtendWith(MockitoExtension.class)\nclass OrderServiceTest {\n\n    @Mock OrderRepository repository;\n    @InjectMocks OrderService service;\n\n    @Test\n    void throwsExceptionIfOrderDoesNotExist() {\n        when(repository.findById(\"X\")).thenReturn(Optional.empty());\n\n        assertThrows(OrderNotFoundException.class, () -&gt; service.read(\"X\"));\n    }\n}<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Web layer: @WebMvcTest<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>@WebMvcTest(OrderController.class)\nclass OrderControllerTest {\n\n    @Autowired MockMvc mvc;\n    @MockitoBean OrderService service;   \/\/ @MockBean in versions earlier than Spring Boot 3.4\n\n    @Test\n    void rejectsAnOrderWithoutCustomer() throws Exception {\n        mvc.perform(post(\"\/api\/v1\/orders\")\n                        .contentType(MediaType.APPLICATION_JSON)\n                        .content(\"{\\\"amount\\\": 10}\"))\n                .andExpect(status().isBadRequest());\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">For repositories, <code>@DataJpaTest<\/code>, and if you use a real database in your tests, Testcontainers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">12. Expose the service\u2019s health with Actuator<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Actuator provides health and metrics endpoints ready for Kubernetes and for monitoring. Expose only the ones you need:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>management:\n  endpoints:\n    web:\n      exposure:\n        include: health,info,prometheus   # only what is needed\n  endpoint:\n    health:\n      probes:\n        enabled: true                     # \/actuator\/health\/liveness and \/readiness for Kubernetes<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">13. Automate quality<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A common format applied automatically (for example, Spotless) so that reviews talk about logic and not whitespace.<\/li>\n\n\n<li>Static analysis in the IDE (SonarLint) and in the pipeline (SonarQube or SonarCloud) with a quality gate.<\/li>\n\n\n<li>Automatic dependency updates (Dependabot or Renovate) so vulnerabilities don\u2019t pile up.<\/li>\n\n\n<li>Tests and analysis mandatory on every pull request before merging.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Common errors<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Field injection with @Autowired<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It works, but it hides dependencies, prevents <code>final<\/code> fields and forces you to use Spring or reflection to test. Move it to the constructor (step 2).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Returning JPA entities from the API<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It exposes internal fields and can trigger lazy loading of relationships during serialisation (or fail with <code>LazyInitializationException<\/code>). Use DTOs (step 3).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">@Transactional that does nothing<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Spring applies transactions through a proxy: they do not work on <code>private<\/code> methods or when a method calls another one in the <strong>same<\/strong> class. Put it on public methods called from outside.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">N+1 queries<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Iterating over a list of entities and accessing a lazy relationship fires one query per element. Use <code>JOIN FETCH<\/code> or <code>@EntityGraph<\/code> in the repository, and disable <code>spring.jpa.open-in-view<\/code> to catch it early.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Catching Exception and carrying on as if nothing happened<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">An empty <code>catch (Exception e) {}<\/code> 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).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Secrets in application.yml<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">System.out.println instead of logs<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It has no levels, does not reach the environment\u2019s logging system and cannot be filtered. Use SLF4J (step 8).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Next steps<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Document the API with springdoc-openapi and review its contract (see the OpenAPI 3 contract with OAuth and API Key guide).<\/li>\n\n\n<li>Build the container image without a Dockerfile with <code>.\/mvnw spring-boot:build-image<\/code>.<\/li>\n\n\n<li>Set up the testing, analysis and deployment pipeline (see the CI\/CD with GitHub Actions guide).<\/li>\n\n\n<li>Add metrics with Micrometer and Prometheus, and distributed tracing with OpenTelemetry.<\/li>\n\n<\/ul>\n\n\n","protected":false},"excerpt":{"rendered":"<p>The practices that make the biggest difference in a Spring Boot service: structure, constructor injection, DTOs, validation, errors, configuration, transactions, logs, comments, tests and automated quality.<\/p>\n","protected":false},"featured_media":0,"template":"","bf_tecnologia":[105],"bf_nivel":[108],"class_list":["post-5172","bf_guia","type-bf_guia","status-publish","hentry","bf_tecnologia-development","bf_nivel-basic"],"acf":[],"_links":{"self":[{"href":"https:\/\/bitflow-solutions.com\/en\/wp-json\/wp\/v2\/bf_guia\/5172","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bitflow-solutions.com\/en\/wp-json\/wp\/v2\/bf_guia"}],"about":[{"href":"https:\/\/bitflow-solutions.com\/en\/wp-json\/wp\/v2\/types\/bf_guia"}],"version-history":[{"count":0,"href":"https:\/\/bitflow-solutions.com\/en\/wp-json\/wp\/v2\/bf_guia\/5172\/revisions"}],"wp:attachment":[{"href":"https:\/\/bitflow-solutions.com\/en\/wp-json\/wp\/v2\/media?parent=5172"}],"wp:term":[{"taxonomy":"bf_tecnologia","embeddable":true,"href":"https:\/\/bitflow-solutions.com\/en\/wp-json\/wp\/v2\/bf_tecnologia?post=5172"},{"taxonomy":"bf_nivel","embeddable":true,"href":"https:\/\/bitflow-solutions.com\/en\/wp-json\/wp\/v2\/bf_nivel?post=5172"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}