CL

clean-architecture

Provides patterns for Clean Architecture and Domain-Driven Design in Spring Boot.

Install

mkdir -p .claude/skills/clean-architecture && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/15715" && unzip -o skill.zip -d .claude/skills/clean-architecture && rm skill.zip

Installs to .claude/skills/clean-architecture

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Provides implementation patterns for Clean Architecture, Hexagonal Architecture (Ports & Adapters), and Domain-Driven Design in Java 21+ Spring Boot 3.5+ applications. Use when structuring layered architectures, separating domain logic from frameworks, implementing ports and adapters, creating entities/value objects/aggregates, or refactoring monolithic codebases for testability and maintainability.
402 chars✓ has a “when” triggerlonger than Claude Code's old 250-char listing cap (fine on current versions)
Advanced

Key capabilities

  • Structure new Spring Boot applications with clear separation of concerns
  • Refactor tightly coupled code into testable, layered architectures
  • Implement domain logic independent of frameworks and infrastructure
  • Design ports and adapters for swappable implementations
  • Apply Domain-Driven Design tactical patterns like entities and aggregates
  • Create testable business logic without Spring context dependencies

How it works

It guides the organization of application code into distinct layers: Domain, Application, Infrastructure, and Adapter, enforcing dependency rules where inner layers are framework-independent.

Inputs & outputs

You give it
Java 21+ Spring Boot 3.5+ application code
You get back
Application structured with Clean Architecture, Hexagonal Architecture, and DDD patterns

When to use clean-architecture

  • Structure Spring Boot app with Clean Architecture
  • Implement domain-driven design aggregates
  • Separate business logic from Spring context
  • Design ports and adapters for services

About this skill

Clean Architecture, Hexagonal Architecture & DDD for Spring Boot

Overview

This skill provides comprehensive guidance for implementing Clean Architecture, Hexagonal Architecture (Ports & Adapters), and Domain-Driven Design tactical patterns in Java 21+ Spring Boot 3.5+ applications. It ensures clear separation of concerns, framework-independent domain logic, and highly testable codebases through proper layering and dependency management.

When to Use

  • Architecting new Spring Boot applications with clear separation of concerns
  • Refactoring tightly coupled code into testable, layered architectures
  • Implementing domain logic independent of frameworks and infrastructure
  • Designing ports and adapters for swappable implementations
  • Applying Domain-Driven Design tactical patterns (entities, value objects, aggregates)
  • Creating testable business logic without Spring context dependencies
  • Trigger phrases: "implement clean architecture", "ports and adapters pattern", "separate domain from infrastructure", "hexagonal architecture Spring Boot", "DDD aggregate design"

Instructions

1. Understand the Core Concepts

Clean Architecture Layers (Dependency Rule)

Dependencies flow inward. Inner layers know nothing about outer layers.

LayerResponsibilitySpring Boot Equivalent
DomainEntities, value objects, domain events, repository interfacesdomain/ - no Spring annotations
ApplicationUse cases, application services, DTOs, portsapplication/ - @Service, @Transactional
InfrastructureFrameworks, database, external APIsinfrastructure/ - @Repository, @Entity
AdapterControllers, presenters, external gatewaysadapter/ - @RestController

Hexagonal Architecture (Ports & Adapters)

  • Domain Core: Pure Java business logic, no framework dependencies
  • Ports: Interfaces defining contracts (driven and driving)
  • Adapters: Concrete implementations (JPA, REST, messaging)

Domain-Driven Design Tactical Patterns

  • Entities: Objects with identity and lifecycle (e.g., Order, Customer)
  • Value Objects: Immutable, defined by attributes (e.g., Money, Email)
  • Aggregates: Consistency boundary with root entity
  • Domain Events: Capture significant business occurrences
  • Repositories: Persistence abstraction, implemented in infrastructure

2. Organize Package Structure

Follow this feature-based package organization:

com.example.order/
├── domain/
│   ├── model/              # Entities, value objects
│   ├── event/              # Domain events
│   ├── repository/         # Repository interfaces (ports)
│   └── exception/          # Domain exceptions
├── application/
│   ├── port/in/            # Driving ports (use case interfaces)
│   ├── port/out/           # Driven ports (external service interfaces)
│   ├── service/            # Application services
│   └── dto/                # Request/response DTOs
├── infrastructure/
│   ├── persistence/        # JPA entities, repository adapters
│   └── external/           # External service adapters
└── adapter/
    └── rest/               # REST controllers

3. Implement the Domain Layer (Framework-Free)

The domain layer must have zero dependencies on Spring or any framework.

  • Use Java records for immutable value objects with built-in validation
  • Place business logic in entities, not services (Rich Domain Model)
  • Define repository interfaces (ports) in the domain layer
  • Use strongly-typed IDs to prevent ID confusion
  • Implement domain events for decoupling side effects
  • Use factory methods for entity creation to enforce invariants

4. Implement the Application Layer

  • Create use case interfaces (driving ports) in application/port/in/
  • Create external service interfaces (driven ports) in application/port/out/
  • Implement application services with @Service and @Transactional
  • Use DTOs for request/response, separate from domain models
  • Publish domain events after successful operations

5. Implement the Infrastructure Layer (Adapters)

  • Create JPA entities in infrastructure/persistence/
  • Implement repository adapters that map between domain and JPA entities
  • Use MapStruct or manual mappers for domain-JPA conversion
  • Configure conditional beans for swappable implementations
  • Keep infrastructure concerns isolated from domain logic

6. Implement the Adapter Layer (REST)

  • Create REST controllers in adapter/rest/
  • Inject use case interfaces, not implementations
  • Use Bean Validation on DTOs
  • Return proper HTTP status codes and responses
  • Handle exceptions with global exception handlers

7. Apply Best Practices

  1. Dependency Rule: Domain has zero dependencies on Spring or other frameworks
  2. Immutable Value Objects: Use Java records for value objects with built-in validation
  3. Rich Domain Models: Place business logic in entities, not services
  4. Repository Pattern: Domain defines interface, infrastructure implements
  5. Domain Events: Decouple side effects from primary operations
  6. Constructor Injection: Mandatory dependencies via final fields
  7. DTO Mapping: Separate domain models from API contracts
  8. Transaction Boundaries: Place @Transactional in application services

8. Write Tests

  • Domain Tests: Pure unit tests without Spring context, fast execution
  • Application Tests: Unit tests with mocked ports using Mockito
  • Infrastructure Tests: Integration tests with @DataJpaTest and Testcontainers
  • Adapter Tests: Controller tests with @WebMvcTest

Examples

Example 1: Domain Layer - Entity with Domain Events

// domain/model/Order.java
public class Order {
    private final OrderId id;
    private final List<OrderItem> items;
    private Money total;
    private OrderStatus status;
    private final List<DomainEvent> domainEvents = new ArrayList<>();

    private Order(OrderId id, List<OrderItem> items) {
        this.id = id;
        this.items = new ArrayList<>(items);
        this.status = OrderStatus.PENDING;
        calculateTotal();
    }

    public static Order create(List<OrderItem> items) {
        validateItems(items);
        Order order = new Order(OrderId.generate(), items);
        order.domainEvents.add(new OrderCreatedEvent(order.id, order.total));
        return order;
    }

    public void confirm() {
        if (status != OrderStatus.PENDING) {
            throw new DomainException("Only pending orders can be confirmed");
        }
        this.status = OrderStatus.CONFIRMED;
    }

    public List<DomainEvent> getDomainEvents() {
        return List.copyOf(domainEvents);
    }

    public void clearDomainEvents() {
        domainEvents.clear();
    }
}

Example 2: Domain Layer - Value Object with Validation

// domain/model/Money.java (Value Object)
public record Money(BigDecimal amount, Currency currency) {
    public Money {
        if (amount.compareTo(BigDecimal.ZERO) < 0) {
            throw new DomainException("Amount cannot be negative");
        }
    }

    public static Money zero() {
        return new Money(BigDecimal.ZERO, Currency.getInstance("EUR"));
    }

    public Money add(Money other) {
        if (!this.currency.equals(other.currency)) {
            throw new DomainException("Currency mismatch");
        }
        return new Money(this.amount.add(other.amount), this.currency);
    }
}

Example 3: Domain Layer - Repository Port

// domain/repository/OrderRepository.java (Port)
public interface OrderRepository {
    Order save(Order order);
    Optional<Order> findById(OrderId id);
}

Example 4: Application Layer - Use Case and Service

// application/port/in/CreateOrderUseCase.java
public interface CreateOrderUseCase {
    OrderResponse createOrder(CreateOrderRequest request);
}

// application/dto/CreateOrderRequest.java
public record CreateOrderRequest(
    @NotNull UUID customerId,
    @NotEmpty List<OrderItemRequest> items
) {}

// application/service/OrderService.java
@Service
@RequiredArgsConstructor
@Transactional
public class OrderService implements CreateOrderUseCase {
    private final OrderRepository orderRepository;
    private final PaymentGateway paymentGateway;
    private final DomainEventPublisher eventPublisher;

    @Override
    public OrderResponse createOrder(CreateOrderRequest request) {
        List<OrderItem> items = mapItems(request.items());
        Order order = Order.create(items);

        PaymentResult payment = paymentGateway.charge(order.getTotal());
        if (!payment.successful()) {
            throw new PaymentFailedException("Payment failed");
        }

        order.confirm();
        Order saved = orderRepository.save(order);
        publishEvents(order);

        return OrderMapper.toResponse(saved);
    }

    private void publishEvents(Order order) {
        order.getDomainEvents().forEach(eventPublisher::publish);
        order.clearDomainEvents();
    }
}

Example 5: Infrastructure Layer - JPA Entity and Adapter

// infrastructure/persistence/OrderJpaEntity.java
@Entity
@Table(name = "orders")
public class OrderJpaEntity {
    @Id
    private UUID id;
    @Enumerated(EnumType.STRING)
    private OrderStatus status;
    private BigDecimal totalAmount;
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    private List<OrderItemJpaEntity> items;
}

// infrastructure/persistence/OrderRepositoryAdapter.java
@Component
@RequiredArgsConstructor
public class OrderRepositoryAdapter implements OrderRepository {
    private final OrderJpaRepository jpaRepository;
    private final OrderJpaMapper mapper;

    @Override
    public Order save(Order order) {
        OrderJpaEntity entity = mapper.toEntity(order);
        return mapper.toDomain(jpaRepository.save(entity));
    }

    @Override
    public Optional<Order> 

---

*Content truncated.*

When not to use it

  • When adding Spring annotations to domain classes
  • When dependencies point outward from the domain layer
  • When framework-specific code is not isolated to infrastructure and adapter layers

Limitations

  • Domain layer must not contain Spring annotations
  • Dependencies must flow inward from outer to inner layers
  • Framework-specific code must remain in infrastructure and adapter layers

How it compares

This approach separates domain logic from frameworks, unlike monolithic designs where business logic is often tightly coupled with infrastructure concerns.

Compared to similar skills

clean-architecture side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
clean-architecture (this skill)02moNo flagsAdvanced
java-pro344moNo flagsAdvanced
backend-microservice-development23moNo flagsIntermediate
microservice-infrastructure43moNo flagsIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

You might also like

java-pro

sickn33

Master Java 21+ with modern features like virtual threads, pattern matching, and Spring Boot 3.x. Expert in the latest Java ecosystem including GraalVM, Project Loom, and cloud-native patterns. Use PROACTIVELY for Java development, microservices architecture, or performance optimization.

3492

backend-microservice-development

TencentBlueKing

后端微服务开发规范,涵盖目录结构、分层架构(API/Service/DAO)、依赖注入、配置管理、Spring Boot 最佳实践。当用户进行后端开发、创建新微服务、编写 Kotlin/Java 代码或设计服务架构时使用。

213

microservice-infrastructure

TencentBlueKing

微服务基础设施指南,涵盖条件配置、事件驱动架构、服务间通信、国际化与日志等微服务架构的核心基础设施。当用户实现服务间调用、配置多环境、实现异步通信、处理国际化或规范日志输出时使用。

411

common-technical-practices

TencentBlueKing

通用技术实践指南,涵盖 AOP 切面、分布式锁、重试机制、参数校验、性能监控、定时任务、审计日志等后端开发中的常见技术实践。当用户需要实现横切关注点、处理并发控制、配置重试策略、添加性能监控或实现审计功能时使用。

26

spring-boot-4-conventions

loiane

Spring Framework 7 / Spring Boot 4 idioms and defaults. Use when writing or reviewing controllers, services, configuration, HTTP clients, async/virtual-thread code, or anything touching Spring's programming model.

00

Context7 MCP Rule

dlwlrmjlo

Always use the Context7 MCP server when foundational planning or architecture decisions are being made.

00

Search skills

Search the agent skills registry