六邊形架構,也被稱為端口與適配器架構或洋葱架構,是一種將業務邏輯與外部依賴解耦的架構模式。

本文將介紹在SpringBoot中實現六邊形架構的三種不同方式。

一、六邊形架構基本原理

1.1 核心概念

六邊形架構由Alistair Cockburn於2005年提出,其核心思想是將應用程序的內部業務邏輯與外部交互隔離開來。這種架構主要由三部分組成:

  • 領域(Domain) :包含業務邏輯和領域模型,是應用程序的核心
  • 端口(Ports) :定義應用程序與外部世界交互的接口
  • 適配器(Adapters) :實現端口接口,連接外部世界與應用程序

1.2 端口分類

端口通常分為兩類:

  • 輸入端口(Primary/Driving Ports) :允許外部系統驅動應用程序,如REST API、命令行接口
  • 輸出端口(Secondary/Driven Ports) :允許應用程序驅動外部系統,如數據庫、消息隊列、第三方服務

1.3 六邊形架構的優勢

  • 業務邏輯獨立性:核心業務邏輯不依賴於特定技術框架
  • 可測試性:業務邏輯可以在沒有外部依賴的情況下進行測試
  • 靈活性:可以輕鬆替換技術實現而不影響業務邏輯
  • 關注點分離:明確區分了業務規則和技術細節
  • 可維護性:使代碼結構更加清晰,便於維護和擴展

二、經典六邊形架構實現

2.1 項目結構

經典六邊形架構嚴格遵循原始設計理念,通過明確的包結構分離領域邏輯和適配器:

src/main/java/com/example/demo/
├── domain/                  # 領域層
│   ├── model/               # 領域模型
│   ├── service/             # 領域服務
│   └── port/                # 端口定義
│       ├── incoming/        # 輸入端口
│       └── outgoing/        # 輸出端口
├── adapter/                 # 適配器層
│   ├── incoming/            # 輸入適配器
│   │   ├── rest/            # REST API適配器
│   │   └── scheduler/       # 定時任務適配器
│   └── outgoing/            # 輸出適配器
│       ├── persistence/     # 持久化適配器
│       └── messaging/       # 消息適配器
└── application/             # 應用配置
    └── config/              # Spring配置類

2.2 代碼實現

2.2.1 領域模型

// 領域模型
package com.example.demo.domain.model;

public class Product {
    private Long id;
    private String name;
    private double price;
    private int stock;
    
    // 構造函數、getter和setter
    
    // 領域行為
    public boolean isAvailable() {
        return stock > 0;
    }
    
    public void decreaseStock(int quantity) {
        if (quantity > stock) {
            throw new IllegalArgumentException("Not enough stock");
        }
        this.stock -= quantity;
    }
}

2.2.2 輸入端口

// 輸入端口(用例接口)
package com.example.demo.domain.port.incoming;

import com.example.demo.domain.model.Product;
import java.util.List;
import java.util.Optional;

public interface ProductService {
    List<Product> getAllProducts();
    Optional<Product> getProductById(Long id);
    Product createProduct(Product product);
    void updateStock(Long productId, int quantity);
}

2.2.3 輸出端口

// 輸出端口(存儲庫接口)
package com.example.demo.domain.port.outgoing;

import com.example.demo.domain.model.Product;
import java.util.List;
import java.util.Optional;

public interface ProductRepository {
    List<Product> findAll();
    Optional<Product> findById(Long id);
    Product save(Product product);
    void deleteById(Long id);
}

2.2.4 領域服務實現

// 領域服務實現
package com.example.demo.domain.service;

import com.example.demo.domain.model.Product;
import com.example.demo.domain.port.incoming.ProductService;
import com.example.demo.domain.port.outgoing.ProductRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class ProductServiceImpl implements ProductService {
    
    private final ProductRepository productRepository;
    
    public ProductServiceImpl(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }
    
    @Override
    public List<Product> getAllProducts() {
        return productRepository.findAll();
    }
    
    @Override
    public Optional<Product> getProductById(Long id) {
        return productRepository.findById(id);
    }
    
    @Override
    public Product createProduct(Product product) {
        return productRepository.save(product);
    }
    
    @Override
    @Transactional
    public void updateStock(Long productId, int quantity) {
        Product product = productRepository.findById(productId)
            .orElseThrow(() -> new RuntimeException("Product not found"));
        
        product.decreaseStock(quantity);
        productRepository.save(product);
    }
}

2.2.5 輸入適配器(REST API)

// REST適配器
package com.example.demo.adapter.incoming.rest;

import com.example.demo.domain.model.Product;
import com.example.demo.domain.port.incoming.ProductService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/products")
public class ProductController {
    
    private final ProductService productService;
    
    public ProductController(ProductService productService) {
        this.productService = productService;
    }
    
    @GetMapping
    public List<Product> getAllProducts() {
        return productService.getAllProducts();
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<Product> getProductById(@PathVariable Long id) {
        return productService.getProductById(id)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }
    
    @PostMapping
    public Product createProduct(@RequestBody Product product) {
        return productService.createProduct(product);
    }
    
    @PutMapping("/{id}/stock")
    public ResponseEntity<Void> updateStock(
            @PathVariable Long id,
            @RequestParam int quantity) {
        productService.updateStock(id, quantity);
        return ResponseEntity.ok().build();
    }
}

2.2.6 輸出適配器(持久化)

// JPA實體
package com.example.demo.adapter.outgoing.persistence.entity;

import javax.persistence.*;

@Entity
@Table(name = "products")
public class ProductEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private double price;
    private int stock;
    
    // 構造函數、getter和setter
}

// JPA倉庫
package com.example.demo.adapter.outgoing.persistence.repository;

import com.example.demo.adapter.outgoing.persistence.entity.ProductEntity;
import org.springframework.data.jpa.repository.JpaRepository;

public interface JpaProductRepository extends JpaRepository<ProductEntity, Long> {
}

// 持久化適配器
package com.example.demo.adapter.outgoing.persistence;

import com.example.demo.adapter.outgoing.persistence.entity.ProductEntity;
import com.example.demo.adapter.outgoing.persistence.repository.JpaProductRepository;
import com.example.demo.domain.model.Product;
import com.example.demo.domain.port.outgoing.ProductRepository;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Component
public class ProductRepositoryAdapter implements ProductRepository {
    
    private final JpaProductRepository jpaRepository;
    
    public ProductRepositoryAdapter(JpaProductRepository jpaRepository) {
        this.jpaRepository = jpaRepository;
    }
    
    @Override
    public List<Product> findAll() {
        return jpaRepository.findAll().stream()
            .map(this::mapToDomain)
            .collect(Collectors.toList());
    }
    
    @Override
    public Optional<Product> findById(Long id) {
        return jpaRepository.findById(id)
            .map(this::mapToDomain);
    }
    
    @Override
    public Product save(Product product) {
        ProductEntity entity = mapToEntity(product);
        ProductEntity savedEntity = jpaRepository.save(entity);
        return mapToDomain(savedEntity);
    }
    
    @Override
    public void deleteById(Long id) {
        jpaRepository.deleteById(id);
    }
    
    private Product mapToDomain(ProductEntity entity) {
        Product product = new Product();
        product.setId(entity.getId());
        product.setName(entity.getName());
        product.setPrice(entity.getPrice());
        product.setStock(entity.getStock());
        return product;
    }
    
    private ProductEntity mapToEntity(Product product) {
        ProductEntity entity = new ProductEntity();
        entity.setId(product.getId());
        entity.setName(product.getName());
        entity.setPrice(product.getPrice());
        entity.setStock(product.getStock());
        return entity;
    }
}

2.3 優缺點分析

優點:

  • 結構清晰,嚴格遵循六邊形架構原則
  • 領域模型完全獨立,不受技術框架影響
  • 適配器隔離了所有外部依賴
  • 高度可測試,可以輕鬆模擬任何外部組件

缺點:

  • 代碼量較大,需要編寫更多的接口和適配器
  • 對象映射工作增加,需要在適配器中轉換領域對象和持久化對象
  • 可能感覺過度設計,特別是對簡單應用程序
  • 學習曲線較陡峭,團隊需要深入理解六邊形架構

2.4 適用場景

  • 複雜的業務領域,需要清晰隔離業務規則
  • 長期維護的核心繫統
  • 團隊已熟悉六邊形架構原則
  • 需要靈活替換技術實現的場景

三、基於DDD的六邊形架構

3.1 項目結構

基於DDD的六邊形架構結合了領域驅動設計的概念,進一步豐富了領域層:

src/main/java/com/example/demo/
├── domain/                  # 領域層
│   ├── model/               # 領域模型
│   │   ├── aggregate/       # 聚合
│   │   ├── entity/          # 實體
│   │   └── valueobject/     # 值對象
│   ├── service/             # 領域服務
│   └── repository/          # 倉儲接口
├── application/             # 應用層
│   ├── port/                # 應用服務接口
│   │   ├── incoming/        # 輸入端口
│   │   └── outgoing/        # 輸出端口
│   └── service/             # 應用服務實現
├── infrastructure/          # 基礎設施層
│   ├── adapter/             # 適配器
│   │   ├── incoming/        # 輸入適配器
│   │   └── outgoing/        # 輸出適配器
│   └── config/              # 配置類
└── interface/               # 接口層
    ├── rest/                # REST接口
    ├── graphql/             # GraphQL接口
    └── scheduler/           # 定時任務

3.2 代碼實現

3.2.1 領域模型

// 值對象
package com.example.demo.domain.model.valueobject;

public class Money {
    private final BigDecimal amount;
    private final String currency;
    
    public Money(BigDecimal amount, String currency) {
        this.amount = amount;
        this.currency = currency;
    }
    
    public Money add(Money other) {
        if (!this.currency.equals(other.currency)) {
            throw new IllegalArgumentException("Cannot add different currencies");
        }
        return new Money(this.amount.add(other.amount), this.currency);
    }
    
    // 其他值對象方法
}

// 實體
package com.example.demo.domain.model.entity;

import com.example.demo.domain.model.valueobject.Money;

public class Product {
    private ProductId id;
    private String name;
    private Money price;
    private int stock;
    
    // 構造函數、getter和setter
    
    // 領域行為
    public boolean isAvailable() {
        return stock > 0;
    }
    
    public void decreaseStock(int quantity) {
        if (quantity > stock) {
            throw new IllegalArgumentException("Not enough stock");
        }
        this.stock -= quantity;
    }
}

// 聚合根
package com.example.demo.domain.model.aggregate;

import com.example.demo.domain.model.entity.Product;
import com.example.demo.domain.model.valueobject.Money;

import java.util.ArrayList;
import java.util.List;

public class Order {
    private OrderId id;
    private CustomerId customerId;
    private List<OrderLine> orderLines = new ArrayList<>();
    private OrderStatus status;
    private Money totalAmount;
    
    // 構造函數、getter和setter
    
    // 領域行為
    public void addProduct(Product product, int quantity) {
        if (!product.isAvailable() || product.getStock() < quantity) {
            throw new IllegalArgumentException("Product not available");
        }
        
        OrderLine orderLine = new OrderLine(product.getId(), product.getPrice(), quantity);
        orderLines.add(orderLine);
        recalculateTotal();
    }
    
    public void confirm() {
        if (orderLines.isEmpty()) {
            throw new IllegalStateException("Cannot confirm empty order");
        }
        this.status = OrderStatus.CONFIRMED;
    }
    
    private void recalculateTotal() {
        this.totalAmount = orderLines.stream()
            .map(OrderLine::getSubtotal)
            .reduce(Money.ZERO, Money::add);
    }
}

3.2.2 領域倉儲接口

// 倉儲接口
package com.example.demo.domain.repository;

import com.example.demo.domain.model.aggregate.Order;
import com.example.demo.domain.model.aggregate.OrderId;

import java.util.Optional;

public interface OrderRepository {
    Optional<Order> findById(OrderId id);
    Order save(Order order);
    void delete(OrderId id);
}

3.2.3 應用服務接口

// 應用服務接口
package com.example.demo.application.port.incoming;

import com.example.demo.application.dto.OrderRequest;
import com.example.demo.application.dto.OrderResponse;

import java.util.List;
import java.util.Optional;

public interface OrderApplicationService {
    OrderResponse createOrder(OrderRequest request);
    Optional<OrderResponse> getOrder(String orderId);
    List<OrderResponse> getCustomerOrders(String customerId);
    void confirmOrder(String orderId);
}

3.2.4 應用服務實現

// 應用服務實現
package com.example.demo.application.service;

import com.example.demo.application.dto.OrderRequest;
import com.example.demo.application.dto.OrderResponse;
import com.example.demo.application.port.incoming.OrderApplicationService;
import com.example.demo.application.port.outgoing.ProductRepository;
import com.example.demo.domain.model.aggregate.Order;
import com.example.demo.domain.model.aggregate.OrderId;
import com.example.demo.domain.model.entity.Product;
import com.example.demo.domain.repository.OrderRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class OrderApplicationServiceImpl implements OrderApplicationService {
    
    private final OrderRepository orderRepository;
    private final ProductRepository productRepository;
    
    public OrderApplicationServiceImpl(OrderRepository orderRepository, ProductRepository productRepository) {
        this.orderRepository = orderRepository;
        this.productRepository = productRepository;
    }
    
    @Override
    @Transactional
    public OrderResponse createOrder(OrderRequest request) {
        // 創建訂單領域對象
        Order order = new Order(new CustomerId(request.getCustomerId()));
        
        // 添加產品
        for (OrderRequest.OrderItem item : request.getItems()) {
            Product product = productRepository.findById(new ProductId(item.getProductId()))
                .orElseThrow(() -> new RuntimeException("Product not found"));
            
            order.addProduct(product, item.getQuantity());
            
            // 減少庫存
            product.decreaseStock(item.getQuantity());
            productRepository.save(product);
        }
        
        // 保存訂單
        Order savedOrder = orderRepository.save(order);
        
        // 返回DTO
        return mapToDto(savedOrder);
    }
    
    @Override
    public Optional<OrderResponse> getOrder(String orderId) {
        return orderRepository.findById(new OrderId(orderId))
            .map(this::mapToDto);
    }
    
    @Override
    public List<OrderResponse> getCustomerOrders(String customerId) {
        return orderRepository.findByCustomerId(new CustomerId(customerId)).stream()
            .map(this::mapToDto)
            .collect(Collectors.toList());
    }
    
    @Override
    @Transactional
    public void confirmOrder(String orderId) {
        Order order = orderRepository.findById(new OrderId(orderId))
            .orElseThrow(() -> new RuntimeException("Order not found"));
        
        order.confirm();
        orderRepository.save(order);
    }
    
    private OrderResponse mapToDto(Order order) {
        // 映射邏輯
    }
}

3.2.5 輸入適配器(REST控制器)

// REST控制器
package com.example.demo.interface.rest;

import com.example.demo.application.dto.OrderRequest;
import com.example.demo.application.dto.OrderResponse;
import com.example.demo.application.port.incoming.OrderApplicationService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/orders")
public class OrderController {
    
    private final OrderApplicationService orderService;
    
    public OrderController(OrderApplicationService orderService) {
        this.orderService = orderService;
    }
    
    @PostMapping
    public ResponseEntity<OrderResponse> createOrder(@RequestBody OrderRequest request) {
        OrderResponse response = orderService.createOrder(request);
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/{orderId}")
    public ResponseEntity<OrderResponse> getOrder(@PathVariable String orderId) {
        return orderService.getOrder(orderId)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }
    
    @GetMapping("/customer/{customerId}")
    public List<OrderResponse> getCustomerOrders(@PathVariable String customerId) {
        return orderService.getCustomerOrders(customerId);
    }
    
    @PostMapping("/{orderId}/confirm")
    public ResponseEntity<Void> confirmOrder(@PathVariable String orderId) {
        orderService.confirmOrder(orderId);
        return ResponseEntity.ok().build();
    }
}

3.2.6 輸出適配器(JPA持久化)

// JPA實體
package com.example.demo.infrastructure.adapter.outgoing.persistence.entity;

import javax.persistence.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Entity
@Table(name = "orders")
public class OrderJpaEntity {
    @Id
    private String id;
    
    private String customerId;
    
    @Enumerated(EnumType.STRING)
    private OrderStatusJpa status;
    
    private BigDecimal totalAmount;
    
    private String currency;
    
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "order_id")
    private List<OrderLineJpaEntity> orderLines = new ArrayList<>();
    
    // 構造函數、getter和setter
}

// JPA倉庫
package com.example.demo.infrastructure.adapter.outgoing.persistence.repository;

import com.example.demo.infrastructure.adapter.outgoing.persistence.entity.OrderJpaEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface OrderJpaRepository extends JpaRepository<OrderJpaEntity, String> {
    List<OrderJpaEntity> findByCustomerId(String customerId);
}

// 適配器實現
package com.example.demo.infrastructure.adapter.outgoing.persistence;

import com.example.demo.domain.model.aggregate.Order;
import com.example.demo.domain.model.aggregate.OrderId;
import com.example.demo.domain.model.entity.CustomerId;
import com.example.demo.domain.repository.OrderRepository;
import com.example.demo.infrastructure.adapter.outgoing.persistence.entity.OrderJpaEntity;
import com.example.demo.infrastructure.adapter.outgoing.persistence.repository.OrderJpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Repository
public class OrderRepositoryAdapter implements OrderRepository {
    
    private final OrderJpaRepository jpaRepository;
    
    public OrderRepositoryAdapter(OrderJpaRepository jpaRepository) {
        this.jpaRepository = jpaRepository;
    }
    
    @Override
    public Optional<Order> findById(OrderId id) {
        return jpaRepository.findById(id.getValue())
            .map(this::mapToDomain);
    }
    
    @Override
    public Order save(Order order) {
        OrderJpaEntity entity = mapToJpaEntity(order);
        OrderJpaEntity savedEntity = jpaRepository.save(entity);
        return mapToDomain(savedEntity);
    }
    
    @Override
    public void delete(OrderId id) {
        jpaRepository.deleteById(id.getValue());
    }
    
    @Override
    public List<Order> findByCustomerId(CustomerId customerId) {
        return jpaRepository.findByCustomerId(customerId.getValue()).stream()
            .map(this::mapToDomain)
            .collect(Collectors.toList());
    }
    
    private Order mapToDomain(OrderJpaEntity entity) {
        // 映射邏輯
    }
    
    private OrderJpaEntity mapToJpaEntity(Order order) {
        // 映射邏輯
    }
}

3.3 優缺點分析

優點:

  • 結合DDD概念,更豐富的領域模型
  • 更精確地表達業務規則和約束
  • 領域模型與持久化完全分離
  • 支持複雜業務場景和領域行為

缺點:

  • 架構複雜度進一步增加
  • 學習曲線陡峭,需要同時掌握DDD和六邊形架構
  • 對象映射工作更加繁重
  • 可能過度設計,特別是對簡單領域

3.4 適用場景

  • 複雜業務領域,有豐富的業務規則和約束
  • 大型企業應用,特別是核心業務系統
  • 團隊熟悉DDD和六邊形架構
  • 長期維護的系統,需要適應業務變化

四、簡化版架構實現

4.1 項目結構

簡化架構採用更輕量級的方式實現六邊形架構的核心理念,減少接口數量,簡化層次結構:

src/main/java/com/example/demo/
├── service/                 # 服務層
│   ├── business/            # 業務服務
│   ├── model/               # 數據模型
│   └── exception/           # 業務異常
├── integration/             # 集成層
│   ├── database/            # 數據庫集成
│   ├── messaging/           # 消息集成
│   └── external/            # 外部服務集成
├── web/                     # Web層
│   ├── controller/          # 控制器
│   ├── dto/                 # 數據傳輸對象
│   └── advice/              # 全局異常處理
└── config/                  # 配置

4.2 代碼實現

4.2.1 數據模型

// 業務模型
package com.example.demo.service.model;

import lombok.Data;

@Data
public class Product {
    private Long id;
    private String name;
    private double price;
    private int stock;
    
    // 業務邏輯直接在模型中
    public boolean isAvailable() {
        return stock > 0;
    }
    
    public void decreaseStock(int quantity) {
        if (quantity > stock) {
            throw new IllegalArgumentException("Not enough stock");
        }
        this.stock -= quantity;
    }
}

4.2.2 集成層接口

// 數據庫集成接口
package com.example.demo.integration.database;

import com.example.demo.service.model.Product;
import java.util.List;
import java.util.Optional;

// 沒有複雜的端口和適配器分離,直接定義操作接口
public interface ProductRepository {
    List<Product> findAll();
    Optional<Product> findById(Long id);
    Product save(Product product);
    void deleteById(Long id);
}

4.2.3 業務服務

// 業務服務
package com.example.demo.service.business;

import com.example.demo.integration.database.ProductRepository;
import com.example.demo.service.model.Product;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class ProductService {
    
    private final ProductRepository productRepository;
    
    // 直接注入所需依賴
    public ProductService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }
    
    public List<Product> getAllProducts() {
        return productRepository.findAll();
    }
    
    public Optional<Product> getProductById(Long id) {
        return productRepository.findById(id);
    }
    
    public Product createProduct(Product product) {
        return productRepository.save(product);
    }
    
    @Transactional
    public void updateStock(Long productId, int quantity) {
        Product product = productRepository.findById(productId)
            .orElseThrow(() -> new RuntimeException("Product not found"));
        
        product.decreaseStock(quantity);
        productRepository.save(product);
    }
}

4.2.4 控制器

// REST控制器
package com.example.demo.web.controller;

import com.example.demo.service.business.ProductService;
import com.example.demo.service.model.Product;
import com.example.demo.web.dto.ProductDTO;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/products")
public class ProductController {
    
    private final ProductService productService;
    
    public ProductController(ProductService productService) {
        this.productService = productService;
    }
    
    @GetMapping
    public List<ProductDTO> getAllProducts() {
        return productService.getAllProducts().stream()
            .map(this::toDto)
            .collect(Collectors.toList());
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<ProductDTO> getProductById(@PathVariable Long id) {
        return productService.getProductById(id)
            .map(this::toDto)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }
    
    @PostMapping
    public ProductDTO createProduct(@RequestBody ProductDTO productDto) {
        Product product = toEntity(productDto);
        return toDto(productService.createProduct(product));
    }
    
    @PutMapping("/{id}/stock")
    public ResponseEntity<Void> updateStock(
            @PathVariable Long id,
            @RequestParam int quantity) {
        productService.updateStock(id, quantity);
        return ResponseEntity.ok().build();
    }
    
    private ProductDTO toDto(Product product) {
        ProductDTO dto = new ProductDTO();
        dto.setId(product.getId());
        dto.setName(product.getName());
        dto.setPrice(product.getPrice());
        dto.setStock(product.getStock());
        return dto;
    }
    
    private Product toEntity(ProductDTO dto) {
        Product product = new Product();
        product.setId(dto.getId());
        product.setName(dto.getName());
        product.setPrice(dto.getPrice());
        product.setStock(dto.getStock());
        return product;
    }
}

4.2.5 數據庫實現

// JPA實體 - 與業務模型類似
package com.example.demo.integration.database.entity;

import lombok.Data;
import javax.persistence.*;

@Entity
@Table(name = "products")
@Data
public class ProductEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private double price;
    private int stock;
}

// JPA倉庫
package com.example.demo.integration.database.repository;

import com.example.demo.integration.database.entity.ProductEntity;
import org.springframework.data.jpa.repository.JpaRepository;

public interface JpaProductRepository extends JpaRepository<ProductEntity, Long> {
}

// 倉庫實現
package com.example.demo.integration.database;

import com.example.demo.integration.database.entity.ProductEntity;
import com.example.demo.integration.database.repository.JpaProductRepository;
import com.example.demo.service.model.Product;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Repository
public class ProductRepositoryImpl implements ProductRepository {
    
    private final JpaProductRepository jpaRepository;
    
    public ProductRepositoryImpl(JpaProductRepository jpaRepository) {
        this.jpaRepository = jpaRepository;
    }
    
    @Override
    public List<Product> findAll() {
        return jpaRepository.findAll().stream()
            .map(this::toModel)
            .collect(Collectors.toList());
    }
    
    @Override
    public Optional<Product> findById(Long id) {
        return jpaRepository.findById(id)
            .map(this::toModel);
    }
    
    @Override
    public Product save(Product product) {
        ProductEntity entity = toEntity(product);
        return toModel(jpaRepository.save(entity));
    }
    
    @Override
    public void deleteById(Long id) {
        jpaRepository.deleteById(id);
    }
    
    private Product toModel(ProductEntity entity) {
        Product product = new Product();
        product.setId(entity.getId());
        product.setName(entity.getName());
        product.setPrice(entity.getPrice());
        product.setStock(entity.getStock());
        return product;
    }
    
    private ProductEntity toEntity(Product product) {
        ProductEntity entity = new ProductEntity();
        entity.setId(product.getId());
        entity.setName(product.getName());
        entity.setPrice(product.getPrice());
        entity.setStock(product.getStock());
        return entity;
    }
}

4.3 優缺點分析

優點:

  • 結構簡單,學習曲線平緩
  • 減少了接口和層次數量,代碼量更少
  • 遵循Spring框架慣例,對Spring開發者友好
  • 開發效率高,適合快速迭代
  • 仍然保持了業務邏輯和外部依賴的基本分離

缺點:

  • 分離不如經典六邊形架構嚴格
  • 業務邏輯可能會混入非核心關注點
  • 領域模型不夠豐富
  • 對複雜業務場景支持有限

4.4 適用場景

  • 中小型應用,業務邏輯相對簡單
  • 需要快速開發和迭代的項目
  • 原型或MVP開發
  • 啓動階段的項目,後期可能演進到更嚴格的架構

五、總結

六邊形架構的核心價值在於將業務邏輯與技術細節分離,提高系統的可維護性、可測試性和靈活性。

無論選擇哪種實現方式,都應該堅持這一核心原則,保持領域模型的純粹性和邊界的清晰性。

需要特別説明的是,架構應該服務於業務,而非相反。選擇合適的架構方式,應以提高開發效率、系統質量和業務適應性為目標。