// adapters/persistence/JpaProductRepository.java package com.example.adapters.persistence; import com.example.domain.model.Product; import com.example.domain.spi.ProductRepository; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; import java.util.Optional; @Component @RequiredArgsConstructor public class JpaProductRepository implements ProductRepository private final SpringDataJpaProductRepository jpaRepository;
// application/port/in/CreateProductUseCase.java (Incoming Port) package com.example.application.port.in; import com.example.domain.model.Product; public interface CreateProductUseCase { Product execute(CreateProductCommand command); designing hexagonal architecture with java pdf
record CreateProductCommand(String name, double price, String currency) {} } // adapters/persistence/JpaProductRepository
public interface ProductRepository Optional<Product> findById(String id); void save(Product product); record CreateProductCommand(String name
@PostMapping("/products") public Product createProduct(@RequestBody CreateProductCommand command) return createProductUseCase.execute(command);
Instead of a traditional layered architecture (where the UI depends on Business depends on Data), Hexagonal Architecture places the at the center. External systems interact with the domain through ports (interfaces) and adapters (implementations).
@Override public Optional<Product> findById(String id) return jpaRepository.findById(id).map(this::toDomain);