Please, tell about recommendation for implementation modular monolith on pure Java
- User
Please, tell about recommendation for implementation modular monolith on pure Java
Assistant
Here's a comprehensive guide for implementing a modular monolith in pure Java:
Project Structure
Organize your codebase into distinct modules, each representing a bounded context or business capability:
project-root/ ├── modules/ │ ├── user-management/ │ │ ├── api/ │ │ ├── domain/ │ │ ├── infrastructure/ │ │ └── application/ │ ├── order-processing/ │ ├── inventory/ │ └── shared-kernel/ ├── app/ │ └── Main.java └── build.gradle or pom.xmlKey Implementation Principles
Module Boundaries
Each module should be self-contained with clear boundaries. Use Java packages to enforce these boundaries:
- Keep all module code within its package namespace
- Use package-private visibility as the default
- Expose only necessary APIs through public interfaces
Inter-Module Communication
Design modules to communicate through well-defined interfaces:
// In user-management module public interface UserService { User getUserById(String userId); void createUser(UserDto userDto); } // In order-processing module public class OrderService { private final UserService userService; public OrderService(UserService userService) { this.userService = userService; } }Event-Driven Communication
Implement an in-memory event bus for loose coupling between modules:
public interface EventBus { void publish(DomainEvent event); void subscribe(Class<? extends DomainEvent> eventType, EventHandler handler); } public class InMemoryEventBus implements EventBus { private final Map<Class<?>, List<EventHandler>> handlers = new ConcurrentHashMap<>(); @Override public void publish(DomainEvent event) { handlers.getOrDefault(event.getClass(), Collections.emptyList()) .forEach(handler -> handler.handle(event)); } }Module Registry
Create a central registry for module initialization and dependency injection:
public class ModuleRegistry { private final Map<Class<?>, Object> services = new HashMap<>(); public <T> void register(Class<T> serviceInterface, T implementation) { services.put(serviceInterface, implementation); } @SuppressWarnings("unchecked") public <T> T get(Class<T> serviceInterface) { return (T) services.get(serviceInterface); } }Architecture Patterns
Hexagonal Architecture per Module
Structure each module using hexagonal architecture:
- Domain: Core business logic with no external dependencies
- Application: Use cases and orchestration
- Infrastructure: Database access, external APIs
- API: REST controllers, GraphQL resolvers
Shared Kernel
Create a minimal shared module for:
- Common value objects (Money, Email, etc.)
- Base domain events
- Core interfaces
- Utility classes
Keep the shared kernel small to avoid tight coupling.
Database Strategy
Logical Separation
Use separate schemas or table prefixes for each module:
public class UserRepository { private static final String TABLE_PREFIX = "user_management_"; public User findById(String id) { String sql = "SELECT * FROM " + TABLE_PREFIX + "users WHERE id = ?"; // Execute query } }Transaction Management
Implement a simple transaction manager:
public class TransactionManager { private final Connection connection; public <T> T executeInTransaction(Supplier<T> operation) { try { connection.setAutoCommit(false); T result = operation.get(); connection.commit(); return result; } catch (Exception e) { connection.rollback(); throw new TransactionException(e); } } }Testing Strategy
Module Testing
Test modules in isolation using test doubles:
public class OrderServiceTest { private UserService userService = mock(UserService.class); private OrderService orderService = new OrderService(userService); @Test public void shouldCreateOrderForExistingUser() { when(userService.getUserById("123")).thenReturn(new User("123", "John")); // Test order creation } }Integration Testing
Test module interactions with real implementations:
public class ModuleIntegrationTest { private ModuleRegistry registry; @Before public void setup() { registry = new ModuleRegistry(); // Initialize all modules new UserModule().initialize(registry); new OrderModule().initialize(registry); } }Deployment Considerations
Single Deployment Unit
Package all modules into a single JAR:
- Use Maven modules or Gradle subprojects
- Create a main application class that bootstraps all modules
- Use Java Service Loader for automatic module discovery
Module Lifecycle
Implement a module interface for consistent initialization:
public interface Module { void initialize(ModuleRegistry registry); void start(); void stop(); }Migration Path
This architecture provides a clear migration path to microservices if needed:
- Extract module to separate repository
- Replace in-memory communication with HTTP/messaging
- Deploy as independent service
The modular monolith approach gives you the benefits of modular design without the operational complexity of microservices, making it ideal for many applications that don't require internet-scale distribution.
- User
How use Gradle to enforce module boundaries during development? I have gradle version 6.2.1
Assistant
Here's how to use Gradle 6.2.1 to enforce module boundaries in your modular monolith:
Multi-Module Project Structure
First, set up your project with a multi-module Gradle structure:
project-root/ ├── settings.gradle ├── build.gradle ├── modules/ │ ├── user-management/ │ │ └── build.gradle │ ├── order-processing/ │ │ └── build.gradle │ ├── inventory/ │ │ └── build.gradle │ └── shared-kernel/ │ └── build.gradle └── app/ └── build.gradlesettings.gradle:
rootProject.name = 'modular-monolith' include 'modules:shared-kernel' include 'modules:user-management' include 'modules:order-processing' include 'modules:inventory' include 'app'Enforcing Dependencies
Root build.gradle
Configure common settings and dependency rules:
subprojects { apply plugin: 'java' group = 'com.example.monolith' version = '1.0.0' sourceCompatibility = '11' targetCompatibility = '11' repositories { mavenCentral() } // Enforce that modules can only depend on shared-kernel configurations { implementation { resolutionStrategy { eachDependency { DependencyResolveDetails details -> if (details.requested.group == project.group) { def requestedModule = details.requested.name def currentModule = project.name // Validate allowed dependencies if (!isAllowedDependency(currentModule, requestedModule)) { throw new GradleException( "Module '${currentModule}' cannot depend on '${requestedModule}'. " + "Modules should only communicate through interfaces." ) } } } } } } } def isAllowedDependency(String fromModule, String toModule) { // All modules can depend on shared-kernel if (toModule == 'shared-kernel') return true // App module can depend on any module if (fromModule == 'app') return true // No other cross-module dependencies allowed return false }Module-Specific build.gradle
modules/shared-kernel/build.gradle:
dependencies { // Only external dependencies, no internal module dependencies implementation 'org.slf4j:slf4j-api:1.7.30' }modules/user-management/build.gradle:
dependencies { implementation project(':modules:shared-kernel') // Module-specific dependencies implementation 'com.h2database:h2:1.4.200' testImplementation 'junit:junit:4.13' testImplementation 'org.mockito:mockito-core:3.3.3' } // Expose only API classes jar { include 'com/example/monolith/user/api/**' include 'com/example/monolith/user/dto/**' } // Create a full JAR for internal use task fullJar(type: Jar) { archiveClassifier = 'full' from sourceSets.main.output } artifacts { archives fullJar }Custom Gradle Tasks for Validation
Add these tasks to your root build.gradle:
task validateModuleBoundaries { doLast { subprojects { subproject -> if (subproject.name == 'app' || subproject.name == 'shared-kernel') return def srcDir = file("${subproject.projectDir}/src/main/java") def modulePackage = "com.example.monolith.${subproject.name.replace('-', '')}" // Check for imports from other modules srcDir.eachFileRecurse { file -> if (file.name.endsWith('.java')) { def content = file.text def lines = content.split('\n') lines.each { line -> if (line.startsWith('import')) { validateImport(subproject.name, line, modulePackage) } } } } } } } def validateImport(String moduleName, String importLine, String allowedPackage) { def forbiddenPatterns = [ 'com.example.monolith.user.domain', 'com.example.monolith.user.infrastructure', 'com.example.monolith.order.domain', 'com.example.monolith.order.infrastructure', 'com.example.monolith.inventory.domain', 'com.example.monolith.inventory.infrastructure' ] forbiddenPatterns.each { pattern -> if (importLine.contains(pattern) && !pattern.contains(moduleName.replace('-', ''))) { throw new GradleException( "Module '${moduleName}' has forbidden import: ${importLine}. " + "Cannot import internal packages from other modules." ) } } } // Run validation before build build.dependsOn validateModuleBoundariesSeparate API and Implementation
Create separate source sets for API and implementation:
// In module's build.gradle sourceSets { api { java { srcDir 'src/api/java' } } main { java { srcDir 'src/main/java' } compileClasspath += api.output runtimeClasspath += api.output } } configurations { apiCompile.extendsFrom(implementation) } // Publish only API classes task apiJar(type: Jar) { from sourceSets.api.output archiveClassifier = 'api' } artifacts { archives apiJar } // Other modules depend only on API dependencies { if (project.name != 'shared-kernel') { implementation project(path: ':modules:other-module', configuration: 'apiJar') } }Test Boundary Enforcement
Configure test dependencies to prevent accidental coupling:
// In each module's build.gradle configurations { testImplementation { // Prevent test dependencies from leaking exclude group: project.group, module: '*' } } dependencies { // Explicitly allow only what's needed for tests testImplementation project(':modules:shared-kernel') testImplementation project(path: ':modules:user-management', configuration: 'apiJar') }Integration with CI/CD
Add a comprehensive check task:
task checkModularityRules { dependsOn validateModuleBoundaries doLast { println "All modularity rules passed!" } } check.dependsOn checkModularityRulesUsing Java Package Visibility
Combine Gradle enforcement with Java package structure:
// In user-management module package com.example.monolith.user.api; // Public API public interface UserService { User findById(String id); } // Package-private implementation package com.example.monolith.user.domain; class UserRepository { // package-private // Implementation details }Gradle Properties for Configuration
Create
gradle.propertiesto configure module rules:# Module dependency rules modules.allowCrossDependencies=false modules.enforceApiSeparation=true modules.failOnViolation=trueThen reference in build.gradle:
if (project.hasProperty('modules.failOnViolation') && project.property('modules.failOnViolation') == 'true') { validateModuleBoundaries.doLast { throw new GradleException("Module boundary violation detected!") } }This setup ensures that module boundaries are enforced at compile time, preventing accidental coupling between modules while maintaining the benefits of a monolithic deployment.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.