๐ŸŒ AIๆœ็ดข & ไปฃ็† ไธป้กต
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