Skip to content

A modern template for Java backend development with Spring Boot, applying Domain-Driven Design (DDD) and Clean Architecture principles. Features generic structures, multi-database support, and advanced monitoring.

License

Notifications You must be signed in to change notification settings

Perebati/java-spring-clean-ddd-template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ Spring Boot DDD Template

This project was developed with a focus on scalability, maintainability, and productivity in enterprise application development, by applying Domain-Driven Design (DDD) and Clean Architecture principles.

Java Spring Boot License

πŸ“‹ Table of Contents

🎯 Overview

This template was carefully designed to accelerate backend application development following software engineering best practices. With a solid architecture based on DDD and Clean Architecture, it offers:

  • Highly reusable generic structures for CRUD operations
  • Robust error handling system with automatic logging
  • Advanced monitoring with AOP (Aspect-Oriented Programming)
  • Multi-database support (PostgreSQL, MongoDB, Neo4j)
  • Flexible configuration with multiple execution profiles
  • Automatic documentation with Swagger/OpenAPI

πŸ—οΈ Architecture

Domain-Driven Design (DDD) + Clean Architecture

The project follows a well-defined structure that clearly separates responsibilities:

src/main/java/com/template/app/
β”œβ”€β”€ _shared/                    # Shared components
β”‚   β”œβ”€β”€ application/           # Generic application services
β”‚   β”œβ”€β”€ domain/               # Generic domain entities
β”‚   └── infrastructure/       # Generic infrastructure
β”œβ”€β”€ modules/                  # 🎯 BUSINESS LOGIC
β”‚   └── [your_modules]/      # Specific domain contexts
β”œβ”€β”€ configuration/           # Spring configurations
β”œβ”€β”€ exception/              # Global exception system
β”œβ”€β”€ logging/               # Logging system
└── utils/                # Utilities

Architectural Principles

  1. Separation of Concerns: Each layer has a specific responsibility
  2. Dependency Inversion: Domain doesn't depend on infrastructure
  3. Code Reuse: Generic structures reduce duplication
  4. Testability: Architecture facilitates unit test creation

🎨 Generic Structures

Generic Entity System

The template uses a hierarchical entity system that maximizes code reuse:

Domain Hierarchy

GenericClass                    // Base entity for all domains
└── GenericBusinessClass       // For business entities
    └── [YourEntity]          // Your specific entities

Infrastructure Hierarchy

GenericEntity                   // Base JPA entity
└── GenericBusinessEntity      // For business entities with JPA
    └── [YourEntitySchema]    // Your specific database schemas

Generic Repositories

The repository system offers complete CRUD operations:

// Generic interface with all operations
GenericBusinessRepository<E>

// Implementation with advanced features
GenericBusinessRepositoryImpl<E, S>

Included features:

  • βœ… Synchronous and asynchronous CRUD operations
  • βœ… Paginated queries
  • βœ… Automatic soft delete
  • βœ… Change auditing
  • βœ… User/company access control

Generic Services

Service layer with pre-implemented functionality:

// Generic service with basic operations
GenericServiceImpl<E, R>

Available resources:

  • πŸ” Automatic authentication via MDC
  • πŸ›‘οΈ Standardized exception handling
  • πŸ“Š Optimized read operations
  • ⚑ Asynchronous operation support

πŸ’Ύ Databases

The template comes pre-configured with three databases for different needs:

PostgreSQL (Main Database)

  • Usage: Transactional and relational data
  • Port: 5432
  • Configuration: JPA/Hibernate with schema validation

MongoDB (Logging)

  • Usage: System logs, auditing and analytics
  • Port: 27017
  • Configuration: Spring Data MongoDB

Neo4j (Graphs)

  • Usage: Complex relationships and graph analysis
  • Ports: 7474 (HTTP), 7687 (Bolt)
  • Configuration: Spring Data Neo4j

Docker Compose

Run all databases with one command:

docker-compose up -d

Included services:

  • PostgreSQL + PgAdmin (port 5050)
  • MongoDB
  • Neo4j

πŸ”§ Configuration and Installation

Prerequisites

  • Java 21+
  • Maven 3.8+
  • Docker & Docker Compose

Installation

  1. Clone the repository:
git clone https://github.com/your-user/spring-boot-ddd-template.git
cd spring-boot-ddd-template
  1. Configure environment variables:
cp .env.example .env
# Edit the .env file with your configurations
  1. Start the databases:
docker-compose up -d
  1. Run the project:
mvn spring-boot:run

πŸš€ Execution

Local Execution (Dev)

# Default profile (development)
mvn spring-boot:run

# Or specifying the profile
mvn spring-boot:run -Dspring-boot.run.profiles=dev

Production Build

mvn clean package -Pprod
java -jar target/app-1.0.0-SNAPSHOT.jar --spring.profiles.active=prod

Test Execution

mvn test -Ptest

πŸ“Š Execution Profiles

The project supports multiple profiles for different environments:

πŸ› οΈ Dev (Development)

File: application-dev.yml

spring:
  application:
    name: app-dev
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: validate

Characteristics:

  • Detailed logging enabled
  • Database schema validation
  • Configurations optimized for development

πŸš€ Prod (Production)

File: application-prod.yml

spring:
  application:
    name: app-prod
  jpa:
    hibernate:
      ddl-auto: validate

Characteristics:

  • Performance-optimized configurations
  • Minimal logging
  • Strict schema validation
  • Environment variables for sensitive configurations

πŸ§ͺ Test (Tests)

File: application-test.yml

spring:
  application:
    name: app-test
  jpa:
    hibernate:
      ddl-auto: update

Characteristics:

  • In-memory H2 database
  • Auto table creation
  • Isolated test configurations

Profile Configuration

Each profile can be configured by editing its respective YAML file:

# Example of environment-specific configuration
server:
  port: ${SERVER_PORT:8080}
  
spring:
  datasource:
    url: ${SPRING_DATASOURCE_URL}
    username: ${SPRING_DATASOURCE_USERNAME}
    password: ${SPRING_DATASOURCE_PASSWORD}

πŸ” Monitoring and Logs

AOP System (Aspect-Oriented Programming)

The template includes an advanced monitoring system based on AOP:

SystemMonitor

  • Automatic monitoring of all methods in business modules
  • Exception capture with complete context
  • Asynchronous logging to not impact performance
  • Call tracking with user/company information
@Around("execution(* com.template.app.modules..application..*(..))")
public Object domainMonitor(ProceedingJoinPoint joinPoint) throws Throwable {
    // Automatically monitors all application methods
}

Logging System

Log Structure

  • ErrorLogSchema: Error logs with complete stack trace
  • MethodCallLogSchema: Method call logs
  • RequestLogSchema: HTTP request logs

Storage

All logs are stored in MongoDB for:

  • πŸ“Š Performance analysis
  • πŸ› Advanced debugging
  • πŸ“ˆ Usage metrics
  • πŸ” Complete audit

GlobalExceptionHandler

Robust exception handling system:

@RestControllerAdvice
public class GlobalExceptionHandler {
    // Captures ALL system exceptions
    // Saves logs automatically
    // Returns standardized responses
}

Features:

  • βœ… Automatic capture of all exceptions
  • βœ… Asynchronous logging for performance
  • βœ… Standardized responses for the client
  • βœ… Sensitive information filtering

πŸ“ Swagger/OpenAPI

Automatic Documentation

The project generates automatic API documentation using OpenAPI 3.0:

Access: http://localhost:8080/api/swagger-ui.html

Swagger Configuration

@OpenAPIDefinition(
    info = @Info(title = "Backend API", version = "v1"),
    tags = {
        // Tags organized by business context
    }
)
@SecuritySchemes({
    @SecurityScheme(
        name = "BearerAuth",
        type = SecuritySchemeType.HTTP,
        scheme = "bearer",
        bearerFormat = "JWT"
    )
})

Available Resources

  • πŸ” JWT Authentication integrated in documentation
  • πŸ“‹ Organized tags by business context
  • πŸ§ͺ Direct testing of APIs via interface
  • πŸ“„ Export in standard OpenAPI formats

πŸ§ͺ Tests

Test Structure

The template includes base classes to facilitate test creation:

// Generic test for repositories
GenericBusinessRepositoryTest<E>

// Base configuration for tests
GenericTest

Execution

# All tests
mvn test

# Specific test profile
mvn test -Ptest

# Tests with coverage
mvn test jacoco:report

Test Resources

  • βœ… TestContainers for PostgreSQL
  • βœ… H2 for fast tests
  • βœ… Pre-configured mocks
  • βœ… Automated test data

πŸ› οΈ Customization

Adding New Modules

  1. Create the module structure in src/main/java/com/template/app/modules/[your_module]/
your_module/
β”œβ”€β”€ application/           # Application services
β”‚   β”œβ”€β”€ interfaces/       # Service interfaces
β”‚   └── impl/            # Implementations
β”œβ”€β”€ domain/              # Domain entities
└── infrastructure/      # Repositories and adapters
    β”œβ”€β”€ repository/
    └── mapper/
  1. Extend generic classes:
// Domain
public class YourEntity extends GenericBusinessClass {
    // Your specific fields
}

// Repository
public class YourRepository extends GenericBusinessRepositoryImpl<YourEntity, YourSchema> {
    // Specific implementations
}

// Service
public class YourService extends GenericServiceImpl<YourEntity, YourRepository> {
    // Specific business logic
}

Advanced Configurations

Adding New Database

  1. Configure in application-{profile}.yml
  2. Add dependency in pom.xml
  3. Create Spring configuration in configuration/data/

Customizing Exceptions

  1. Create your specific exception in exception/models/
  2. Add handling in GlobalExceptionHandler

🀝 Contributing

How to Contribute

  1. Fork the project
  2. Create a branch for your feature (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Code Standards

  • Follow SOLID principles
  • Keep test coverage above 80%
  • Use Javadoc to document public methods
  • Follow established naming conventions

Issues and Bug Reports

Use the available issue templates for:

  • πŸ› Report bugs
  • πŸ’‘ Suggest features
  • πŸ“š Improve documentation

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ”— Useful Links

πŸ‘¨β€πŸ’» Author

Lucas Batista Pereira


⭐ If this template was useful to you, consider giving it a star in the repository!

Developed with ❀️ for the Java/Spring Boot community

About

A modern template for Java backend development with Spring Boot, applying Domain-Driven Design (DDD) and Clean Architecture principles. Features generic structures, multi-database support, and advanced monitoring.

Resources

License

Stars

Watchers

Forks

Languages