How to Build a Clean DDD Microservice Architecture: Layers, Naming Rules, and Code Model

This article walks through constructing a welfare‑center microservice using Domain‑Driven Design, detailing a four‑layer architecture, strict naming conventions for POJOs, method naming rules, code‑style guidelines, directory layout, and concrete Java examples for adapters, services, domain objects, and infrastructure components.

HomeTech
HomeTech
HomeTech
How to Build a Clean DDD Microservice Architecture: Layers, Naming Rules, and Code Model

System Architecture

Microservice systems can adopt various architectural styles, but this guide uses the classic layered architecture to implement DDD. The layers separate responsibilities, making business boundaries clear: the domain layer holds core business logic, the application layer orchestrates use cases, the adapter layer exposes APIs, and the infrastructure layer handles persistence, messaging, and remote calls.

Encapsulation and Invocation

The implementation follows four layers:

Adapter Layer : exposes REST, MQ, or job APIs and delegates to the application layer.

Application Layer : thin orchestration layer that composes domain services; it should contain no business logic.

Domain Layer : contains entities, value objects, aggregates, and domain services. It is isolated from technical concerns.

Infrastructure Layer : provides technical implementations such as databases, caches, message queues, and remote RPC, exposing only coarse‑grained interfaces to the domain.

Development Standards

Naming conventions (POJOs) xxxVO – View Object, used for UI display. xxxBO/xxxCO – Client Object (DTO) for data transfer. xxxCmd – Command representing a write request. xxxQuery – Query representing a read request. xxxCmdExe – Command executor (write). xxxQueryExe – Query executor (read). xxxValue – Value object. xxxEntity – Domain entity. xxxDO – Data Object for persistence. xxxInterceptor – Interceptor for aspect logic. xxxService – API service interface. xxxDomainService – Domain service when multiple aggregates cooperate. xxxValidator – Validator class. xxxAssembler – Assembler for DTO ↔ Entity conversion. xxxConvertor – Convertor for Entity ↔ DO conversion. xxxMapper – MyBatis mapper. ResponseTO – Standard response wrapper.

Method naming rules create – Add new record. add – Add (alternative). remove / delete – Delete. update – Update. get – Retrieve single result. list – Retrieve multiple results. page – Paginated query. count – Count query.

Code conventions

Follow Alibaba Java Development Manual naming rules.

Data objects end with DO, DTOs with DTO, VOs with VO.

All POJO fields must use wrapper types; no default values.

Implement Serializable or extend provided base classes.

Provide toString (Lombok optional).

Avoid both isXxx() and getXxx() for the same property.

Code Model Construction

Directory structure

├── pom.xml
├── start
│   └─ src/main/java/cn/autohome/ddd/Application.java
│   └─ src/main/resources/bootstrap.yml
│   └─ src/main/resources/application.yml
│   └─ src/main/resources/logback-spring.xml
├── adapter
│   └─ src/main/java/.../controller/BalanceController.java
│   └─ src/main/java/.../mqhandler/CheckAndSendMQHandler.java
│   └─ src/main/java/.../jobhandler/JobHandler.java
├── app
│   └─ src/main/java/.../command/GiftsAddCmdExe.java
│   └─ src/main/java/.../service/BalanceServiceImpl.java
│   └─ src/main/java/.../service/GiftsServiceImpl.java
├── client
│   └─ src/main/java/.../api/BalanceServiceI.java
│   └─ src/main/java/.../dto/clientobject/GiftsCO.java
│   └─ src/main/java/.../vo/BalanceVo.java
├── domain
│   └─ src/main/java/.../domain/balance/Balance.java
│   └─ src/main/java/.../domain/gifts/Gifts.java
├── infrastructure
│   └─ src/main/java/.../gatewayimpl/GiftsGatewayImpl.java
│   └─ src/main/java/.../gatewayimpl/BalanceGatewayImpl.java
│   └─ src/main/java/.../gatewayimpl/SendGatewayImpl.java
└── pom.xml

Adapter layer example (REST API)

@RestController
@RequestMapping("/balance")
@Api(value = "/balance", tags = "Balance")
public class BalanceController {
    @Autowired
    private BalanceServiceI balanceService;

    @GetMapping("/like")
    @ApiOperation("Query balance")
    public ResponseTO<BalanceVo, DefaultResponseErrorType> balance(){
        return balanceService.getLikeBalance();
    }
}

Application layer example (service implementation)

@Service
public class BalanceServiceImpl implements BalanceServiceI {
    @Resource
    private LikeBalanceQryExe likeBalanceQryExe;

    @Override
    public ResponseTO<BalanceVo, DefaultResponseErrorType> getLikeBalance(){
        OaTokenInfo user = OaWebContextUtil.getTokenWapper().getOaTokenInfo();
        return likeBalanceQryExe.execute(user);
    }
}

Domain layer example (entity and value object)

public class Gifts extends Entity {
    private UserProfile createUser;
    private UserProfile giftsUser;
    private CurrencyTypeEnum currencyType;
    private Long giftsNumber;
    private String giftsMessage;
}

public class UserProfile extends Entity {
    private String userId;
    private String userCode;
    private String userName;
    private String deptCode;
    private String deptName;
}

Infrastructure layer example (gateway implementation)

@Component
@Slf4j
public class GiftsGatewayImpl implements GiftsGateway {
    @Resource
    private GiftsMapper giftsMapper;

    @Override
    public Gifts addGifts(Gifts gifts){
        GiftsDO giftsDO = GiftsConvertor.toDataObject(gifts);
        giftsMapper.add(giftsDO);
        gifts.setGitfsId(giftsDO.getId());
        return gifts;
    }
}

Conclusion

The guide demonstrates how DDD‑driven code organization achieves high cohesion and low coupling by separating concerns into distinct layers, enforcing consistent naming and coding standards, and providing concrete directory and code templates that teams can adapt to their own projects.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend ArchitectureMicroservicesDomain-Driven DesignDDDcode standards
HomeTech
Written by

HomeTech

HomeTech tech sharing

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.