Comprehensive Spring Boot Project Template and Best Practices for Backend Development

This article presents a comprehensive Spring Boot project template for backend development, detailing README guidelines, one‑click local build scripts, business‑oriented package structure, automated test classifications, logging, exception handling, distributed locks, code style, static analysis, health checks, API documentation, database migration, multi‑environment setup, CORS configuration, and recommended third‑party libraries.

Top Architect
Top Architect
Top Architect
Comprehensive Spring Boot Project Template and Best Practices for Backend Development

In many software projects the initial setup—basic code framework, CI infrastructure, and project scaffolding—is often called the "zero‑iteration" work. After a project runs for a while, developers notice missing tests, incomplete architecture, or inconsistent naming. To reduce repetitive effort and provide best‑practice guidance, the author created a public Spring Boot project template for backend services.

README from the Start

A good README gives a quick overview, helps newcomers, and reduces communication cost. It should include project description, technology stack, local build commands, domain model overview, test strategy, architecture diagrams, deployment diagrams, external dependencies, environment information, coding conventions, and FAQ.

One‑Click Local Build

Three scripts simplify onboarding:

idea.sh – generates IntelliJ project files and opens the IDE.

run.sh – starts the application, launches a local database, and opens debug port 5005.

local-build.sh – runs the local build; the build must succeed before committing.

Typical workflow: pull code → run idea.sh → develop and write tests → run run.sh (optional) → run local-build.sh → pull again and commit.

#!/usr/bin/env bash
./gradlew clean bootRun

Directory Structure

The project follows the Maven/Gradle standard layout with two top‑level folders: src for Java sources and gradle for Gradle configuration. The three helper scripts reside in the root.

└── order-backend
    ├── gradle   // Gradle configs
    ├── src      // Java source code
    ├── idea.sh
    ├── local-build.sh
    └── run.sh

Business‑Oriented Packaging

Instead of technical layers (controller, service, infrastructure), packages are organized by domain concepts such as order and product. Each domain package contains its application service, controller, repository, and a model sub‑package for entities and value objects.

├── order
│   ├── OrderApplicationService.java
│   ├── OrderController.java
│   ├── OrderNotFoundException.java
│   ├── OrderRepository.java
│   ├── OrderService.java
│   └── model
│       ├── Order.java
│       ├── OrderFactory.java
│       ├── OrderId.java
│       ├── OrderItem.java
│       └── OrderStatus.java

A common common package holds shared utilities, configuration, and logging.

Automated Test Classification

Three test types are defined:

Unit tests – core domain models and services.

Component tests – classes like repositories that need the application context.

API tests – end‑to‑end tests that start the server.

Gradle source sets separate these tests:

sourceSets {
    componentTest {
        compileClasspath += sourceSets.main.output + sourceSets.test.output
        runtimeClasspath += sourceSets.main.output + sourceSets.test.output
    }
    apiTest {
        compileClasspath += sourceSets.main.output + sourceSets.test.output
        runtimeClasspath += sourceSets.main.output + sourceSets.test.output
    }
}

Corresponding directories are src/test/java, src/componentTest/java, and src/apiTest/java.

Logging

Logback MDC is used to attach a request ID to every log line, and a Redis appender forwards logs to Logstash for centralized analysis.

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
    throws ServletException, IOException {
    String headerRequestId = request.getHeader(HEADER_X_REQUEST_ID);
    MDC.put(REQUEST_ID, isNullOrEmpty(headerRequestId) ? newUuid() : headerRequestId);
    try {
        filterChain.doFilter(request, response);
    } finally {
        clearMdc();
    }
}

Exception Handling

All exceptions extend a common AppException that carries an ErrorCode enum, HTTP status, and a data map for additional context. The error response is standardized via an ErrorDetail DTO.

public abstract class AppException extends RuntimeException {
    private final ErrorCode code;
    private final Map<String, Object> data = newHashMap();
}

Background Tasks & Distributed Locks

Spring’s @EnableAsync and @EnableScheduling configure a thread‑pool executor. ShedLock provides a JDBC‑based distributed lock to guarantee that scheduled jobs run only once in a cluster.

@Configuration
@EnableSchedulerLock(defaultLockAtMostFor = "PT30S")
public class DistributedLockConfiguration {
    @Bean
    public LockProvider lockProvider(DataSource dataSource) {
        return new JdbcTemplateLockProvider(dataSource);
    }
}

Unified Code Style

Checkstyle enforces formatting, and naming conventions such as using Command suffix for request DTOs and Representation for response DTOs are recommended.

Static Code Checks

Gradle plugins for Checkstyle, SpotBugs, OWASP Dependency‑Check, and Sonar are integrated to maintain code quality.

Health Check

A simple endpoint (e.g., /about) returns build metadata and a 200 status, serving both manual verification and load‑balancer health probes.

./run.sh

API Documentation

Swagger (Springfox) auto‑generates API docs from controller annotations. The configuration is active in local and dev profiles.

@Configuration
@EnableSwagger2
@Profile({"local", "dev"})
public class SwaggerConfiguration {
    @Bean
    public Docket api() {
        return new Docket(SWAGGER_2)
                .select()
                .apis(basePackage("com.ecommerce.order"))
                .paths(any())
                .build();
    }
}

Database Migration

Flyway manages schema evolution. Migration scripts reside under src/main/resources/db/migration and follow the V{version}__{description}.sql naming convention.

Multi‑Environment Builds

Profiles for local, ci, dev, qa, uat, and prod allow environment‑specific configuration such as stubbed services or in‑memory databases.

CORS

Global CORS mapping is added via a WebMvcConfigurer. When Spring Security is used, a dedicated CorsConfigurationSource bean ensures CORS handling occurs before security filters.

Common Third‑Party Libraries

Guava

Apache Commons

Mockito

DBUnit

Rest Assured

Jackson 2

jjwt

Lombok

Feign

Tika

iText

Zxing

XStream

Conclusion

The article demonstrates a practical, production‑ready Spring Boot backend template that covers project scaffolding, coding standards, testing strategy, observability, deployment, and documentation. While the practices are simple, applying them systematically can greatly improve team efficiency and code quality.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

DockerBackend Developmentbest practicesSpring BootProject Template
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.