Coding Conventions
개요: 공통 구현 규칙입니다. 템플릿
ExampleItem테이블 세트와 enum 적용 세트에 이미 있는 규칙을 글로 풀어 둔 것입니다. Implementer는 이 문서와 템플릿을 그대로 따릅니다. 예제 소스에서 메서드나 필드를 생략하지 않습니다.
Shared implementation conventions for agent-assisted work. Every rule here is already visible in code under templates/backend/spring/; this page states the rule so a worker does not have to infer it. When this page and the template disagree, report it — do not pick one.
Project-local rules always win over this page (see precedence).
Layering
계층은 접미사가 아니라 책임과 의존으로 구분합니다. 자세한 기준은 애플리케이션 영역과 Facade, 데이터 접근 경계, ADR-0010을 봅니다.
[api] HTTP·gRPC 도메인 진입 ──→ 도메인 진입(Facade 등) ──→ Port → Adapter → Spec
[api] GraphQL·HTTP BFF 진입 ──→ BFF 진입 ──→ 도메인 진입(들) ──→ Port → …
(Port 직접 호출 없음)
| Layer | Owns | Must not |
|---|---|---|
| 진입 (Controller / GraphQL Resolver / gRPC service) | 바인딩만. CommonResponse 등 프로토콜 응답 | Business rules, Repository, open transactions beyond Facade |
| 도메인 애플리케이션 진입 (유스케이스) | 한 도메인 Port CRUD·상태·정책. 불변식과 애그리거트 관리 주체. 이름 기본값은 Facade이며, 접미사 목록은 열려 있음(책임이 분명할 때만 Manager, Checker, Handler, Processor, Resolver 등). 조회 직후 DisplayNameResolver. enum 시 getCode()를 String DTO에 되돌림 | Adapter·entity·Spec·Repository. 다른 도메인 Adapter. 불변식·애그리거트 규칙을 BFF·Controller·Adapter에 두기 |
| BFF 애플리케이션 진입 | 필요할 때만 둡니다. 여러 도메인 애플리케이션 진입을 묶어 화면·시나리오만 조립. 기본 예 {Feature}BffFacade (호스트 기존명 유지 가능) | DomainPort·Adapter·entity·Spec·Repository. 도메인 규칙을 BFF에 재구현. BFF 전용 Port 신설. 도메인 유스케이스만으로 충분한 요청에 BFF를 끼우기 |
| Port | 영속·외부 능력 계약. 도메인 진입만 호출. BFF는 Port를 보지 않음 | HTTP·JPA 타입 |
| JPA Adapter | Specs.of(Filter), map / mapAll, BeanUtils.map on update, entity.delete(). CQRS 적용점: optional Read / Command Provider | HTTP, multi-Port 비즈니스 흐름 |
| Provider | Adapter 아래 기술 접근 (RedisProvider, VaultProvider, …) | Port 이름에 제품명 |
| Repository | JpaRepository + empty custom + JpaSpecificationExecutor | Derived query, business logic |
Port names describe capability (CachePort, EncryptionPort, TokenPort, LockPort, …), not vendor.
See adapter README.
기본 공개 표면은 도메인 애플리케이션 진입(유스케이스) 입니다. 이 영역이 불변식과 애그리거트를 관리하는 주체입니다. 클래스 이름은 열린 상태입니다. 기본값은 Facade이고, 역할이 분명할 때만 다른 접미사를 씁니다.
한 도메인 유스케이스로 응답이 충분하면 진입(HTTP 도메인 Controller, gRPC)이 그 진입점만 호출합니다. BFF는 화면·시나리오가 여러 도메인 진입을 묶어야 할 때 필요 시 둡니다. 클라이언트(웹, 앱)마다 조합이 달라 도메인 API만으로 맞추기 어려울 때도 같습니다.
진입(Controller·GraphQL·gRPC)은 도메인 또는(있을 때) BFF 애플리케이션 진입점만 호출합니다.
도메인 진입은 자기 도메인 Port만 봅니다.
BFF 진입은 도메인 애플리케이션 진입만 호출합니다. DomainPort를 직접 주입·호출하지 않습니다.
Skipping a layer is a Reviewer high finding.
Legacy *Service that only wraps JPA → Adapter by role.
애플리케이션 이름 (열린 상태)
유스케이스 영역의 역할(불변식·애그리거트·정책)과 클래스 이름은 별개입니다. 이름은 닫힌 허용 목록이 아닙니다. 특정 접미사를 일률적으로 강제하지 않습니다. 역할을 가장 잘 설명하도록 고릅니다.
- 기본값은 Facade입니다. 원셋도
ExampleItemFacade입니다. - Manager, Checker, Handler, Processor, Resolver 등은 책임이 분명할 때만 씁니다.
- 이름만 보고 Facade를 Manager 등으로 일괄 변경하지 않습니다.
- 표시명 헬퍼 예는
DisplayNameResolver입니다.UserNameFacade처럼 표시명 전용 Facade는 두지 않습니다.
BFF를 둘 때는 조립(여러 도메인 진입)임이 이름에 드러나게 두는 것이 좋습니다.
기본 예는 {Feature}BffFacade이고, 호스트에 *IntegrationFacade 등이 있으면 호스트를 유지합니다.
| 도메인 애플리케이션 진입 | BFF 애플리케이션 진입 | |
|---|---|---|
| 책임 | 유스케이스·정책·불변식·애그리거트 관리 (기본) | 필요 시 여러 도메인 진입을 묶어 화면·시나리오 조립 |
| 이름 | 열림. 기본 Facade. 책임 분명할 때만 다른 접미 | 기본 예 BffFacade (호스트명 유지 가능) |
| 모노리포 위치 | model | api |
| 모놀리식 위치 | 도메인 폴더 (원셋 facade/) | 앱의 BFF·feature 패키지 |
| 의존 | 자기 Port + DisplayNameResolver | 도메인 애플리케이션 진입만 (Port 없음) |
| 누가 호출 | HTTP 도메인 Controller, gRPC | GraphQL, HTTP BFF |
| 원셋 | ExampleItemFacade | 코드 없음. 이 표만 |
DisplayNameResolver는 도메인 진입과 같이 model(또는 모놀리식 도메인 support/display)에 둡니다.
표시명 치환은 도메인 조회 Facade가 담당하고, BFF는 그 결과를 조합합니다.
도메인 모듈이 영속으로 내주는 계약은 Port이고, 다른 앱·BFF가 호출하는 공개 표면은 도메인 애플리케이션 진입입니다. BFF 전용 Port를 만들지 않으며, BFF가 DomainPort를 직접 보지 않습니다. api의 도메인 Controller·gRPC는 model의 도메인 진입을 호출합니다.
Port / Adapter / Provider / Client는 계층 역할 어휘입니다. Provider나 Client도 Port를 구현하면 Adapter 역할입니다.
GraphQL / gRPC 진입
| 진입 (api) | 호출 | 비고 |
|---|---|---|
| GraphQL | BFF 애플리케이션 진입 | 시나리오 조립이 있을 때. GraphQL을 쓰면 그 진입은 BFF를 거친다 |
| gRPC | 도메인 애플리케이션 진입 (model) | 도메인 proto ↔ 도메인 유스케이스 |
| HTTP 도메인 API | 도메인 애플리케이션 진입 (model) | 기본. ExampleItem 원셋 → Facade |
| HTTP BFF API | BFF 애플리케이션 진입 | 화면·시나리오 조립이 필요할 때. GraphQL과 같은 층 |
다른 프로세스로 나가는 gRPC·HTTP는 도메인 쪽 *ClientPort / *ClientAdapter로 두고, 도메인 진입이 그 Port를 봅니다.
BFF는 로컬·원격 모두 도메인 진입(또는 그에 대응하는 공개 API)만 호출합니다.
원셋에 GraphQL·gRPC 코드는 두지 않습니다.
Repository layout (모놀리식 vs 모노리포)
계층은 같고 모듈·폴더만 갈라집니다. 복사 상세는 ONESET.md입니다.
| 모놀리식 | 모노리포 | |
|---|---|---|
| api / 앱 | 진입(Controller 등) + 필요 시 BFF 애플리케이션 진입. 원셋은 확인용 Controller를 도메인 트리에 둠 | 진입 + 필요 시 BFF 애플리케이션 진입 |
| model | (같은 앱 안 도메인 폴더) 도메인 진입(Facade 등), DisplayNameResolver, dto, Port, Adapter, entity, repository, spec | 동일 구성을 lib-model에. 패키지 도메인만, 모듈 쪼개지 않음 |
| REST 연동 | 앱 client/ 등 | 복사 예 outbound-rest/ (공유 lib 아님, 승격은 나중에) |
@BizEnum 생성물 | 소스에 두지 않음. clean 후 재생성 | 동일. 모듈 경계와 별개 |
Audit
BaseEntity→AuditingEntityListener+BaseEntityListener- 등록만:
CreatedEntity. 수정까지:UpdatedEntity(updatedAt/updatedBy/version) - String PK 자동 생성·서비스 id는
IdGeneratable/ServiceProviderble+ Listener
Display names
- 클래스 이름은
DisplayNameResolver로 통일합니다.UserNameFacade/FarmNameFacade처럼 도메인 접두를 붙이지 않습니다. - 위치는 도메인 진입과 같이 model(모놀리식은 도메인
support/display)입니다. - 도메인 진입이 조회 직후
applyCreatedByDisplayNames/applyAuditorDisplayNames를 호출합니다. BFF는 그 결과를 조합합니다. - Name 맵은 Port
findAllName+Filter.ids(IN) 로만 채웁니다. ItemfindByIds로 대체하지 않습니다. (연관·무거운 컬럼이 끌려옵니다.) - IN으로 묶은 Name 목록 전체를 캐시하지 않습니다. 단건
@Cacheable과는 별개입니다. 원셋 안내는 exampleitem/support/display입니다.
Domain read cache (@Cacheable → CachePort)
- 적용할 때만 cache를 봅니다. 기본 원셋에는 캐시 코드를 넣지 않습니다.
- 호스트에 스택이 없으면 먼저 lib-cache (도메인 없음). Facade·TTL은 cache 변형.
- 흐름:
@Cacheable/@CacheEvict→CachePortCacheManager→CachePort→ Redis. aside 수동 금지. - 값 직렬화는
CacheValueCodec(JSON).Serializable금지. - lib-cache는 default TTL만. 이름·추가 TTL은 model. BFF에는 두지 않음.
- 앱의
RedisCacheManager는 제거. Gateway JWT KV는@Cacheable이 아니라CachePort직접.
무효화
- 단건:
@CacheEvict(key = "#id")(또는#result.id). - 일괄·키 불명:
allEntries = true({CACHE_NAME}::prefix 삭제). - Name IN·목록 검색은 캐시하지 않음.
캐시 값 (약하게)
- 응답 DTO(
Res.Item등) 권장. Entity·프록시·요청 객체는 비권장.
호스트 Redis 체크리스트 (캐시)
StringRedisTemplate+CachePort,@PrimaryCachePortCacheManager.RedisTemplate값이면 JSON. JDK 직렬화 금지.- 앱에
RedisCacheManager/ 중복 CacheManager 없음.
Distributed lock (LockPort / Redisson)
- 공유 모듈: lib-distributed-lock. 캐시(lib-cache/Lettuce)와 분리.
- 기본 watchdog. 고정 lease는 오버로드.
wait내 미획득 → 콜백 미실행. - 반환:
LockResult<T>(acquired, value)(null hit과 missed 구분). - 수동 lock/unlock 금지. DB는 콜백 안 커밋까지 후 반환.
- 짧은 예: lock/ (JWT 키 sync). ExampleItem 락 원셋 실구현 없음.
Redis 키 (캐시·락·KV)
@Cacheable:{CACHE_NAME}::{id}(예:member::42).- 수동 KV:
{영역}:{용도}:…(예:access:…).::쓰지 않음. - 분산 락:
lock:{영역}:{리소스}또는…:{id}—LockKeys.of만 (예:lock:auth-sig:sync). - env/앱 전역 접두는 공유 Redis일 때만. 기본 생략.
Messaging
- 원칙: 오케스트레이션 Saga와 Outbox — 전통 Saga(소비→결정→발행). Outbox로 발행 경로 중앙화. 전 이력 방송으로 이벤트 지옥 만들지 않음.
- 알림 ≠ outbox. 메일·문자·카톡 등 놓쳐도 되는 알림은 AFTER_COMMIT / best-effort. outbox는 재처리·감사가 요구사항일 때만 (ADR-0012).
- 라우팅(실시간·명령): lib-message-routing — Rabbit.
- lib-message-saga: 앱 → REST/gRPC 결과/시작 발행 + Kafka 요청/보상 컨슘. event-saga = Outbox + 오케스트레이션.
- 유스케이스에 사가·신뢰 전달이 필요하면
spring-messaging-saga레시피를 고른다. CRUD 원셋 기본 경로에 비동기를 강제하지 않는다. - 라우팅(Rabbit)과 섞지 않는다.
Naming
| Thing | Convention | Example |
|---|---|---|
| Request DTO holder | {Domain}Req with inner static classes | ExampleItemReq.Ids, Filter, Create, Update |
| Response DTO holder | {Domain}Res with inner static classes | Id, then Name(표시 필드), then Single, then Item |
| Display name helper | DisplayNameResolver | applyCreatedByDisplayNames, findNameMap |
| Domain application entry | 기본 Facade (model). 책임 분명할 때만 Manager/Checker/Handler/Processor/Resolver | ExampleItemFacade, DisplayNameResolver |
| BFF application entry | 기본 예 {Feature}BffFacade (api) | CheckoutBffFacade (원셋 코드 없음) |
| Facade / Controller method | same plain name on both | search, save, saveAll, findById, saveById, deleteById, findAll, findByIds, searchName, findAllName, deleteByIds |
| Port / JPA Adapter method | the same list, unchanged when an enum is applied | search, save, saveAll, findById, saveById, deleteById, findAll, findByIds, searchName, findAllName, deleteByIds |
| Specification holder | {Domain}Specs.of(Filter) only | ExampleItemSpecs.of |
| Entity table | {prefix}_{snake_name} | le_example_item |
| Enum | @BizEnum + CodeValue + code / value | EnHttpMethod, shared EnYn, EnStatus |
One holder class per domain per direction. Do not scatter CreateExampleItemRequest-style top-level classes.
DTO rules
- The template uses Lombok
@Data. Match the host project when it differs. - Req inner classes are only
Ids,Filter,Create,Update. - Res inner classes are only
Id,Name extends Id,Single extends Name,Item extends Single. Nameholds the display field used byDisplayNameResolver/searchName(ExampleItem은url).Filterhasid, thenids, then the column filters, thenstartAtandendAt.- Enum columns stay
Stringon every DTO. Do not storeenum.name(). - 목록 페이징은
PageQuery(DEFAULT_SIZE20,MAX_SIZE100,resolvedSize클램프).Filter(또는WebListQuery)가PageQuery를 확장하고, 컨트롤러는filter.toPageable()을 Facade에 넘깁니다. - 게이트웨이처럼 DB 목록이 없고 Spring
Pageable만 쓰는 호스트는PageQuery를 강제하지 않습니다.
Transactions
- Class-level
@Transactional(readOnly = true, transactionManager = "transactionManager")on both Facade and JPA Adapter. - Write methods override with
@Transactionalat the method. - Adapter transactions join the Facade. Do not start a transaction in the Controller.
Persistence
- Repository =
JpaRepository+ an empty custom repository +JpaSpecificationExecutor. No derived query methods. Single get isfindById. findByIdsanddeleteByIdsfillFilter.idsand callSpecs.of. Ifidsis null or empty, return without querying.- One spec factory:
of(Filter).equalper column,inonidforids,goe/loeonCreatedEntity.createdAtforstartAt/endAt. delete()is empty until a status column exists. Do not callrepository.delete.- A column with a database
DEFAULThas no field initializer and no@Builder.Default.@DynamicInsertomits the null column so the database default is stored. - Enum equality in a spec passes the enum from
ofNullable, not the raw string. See the enum template.
Partial update
saveById loads the entity and calls BeanUtils.map(update, entity).
Null and blank strings are not updates.
Never overwrite with null on update.
Mapping
ModelMapperUtil.mapandmapAllconvert DTO ↔ entity and entity →Res.- On enum apply,
BizEnumProcessoremits_Enumwith@Converter(autoApply = true). JPA loads that class. Its static block registers two converters onModelMapperUtil.modelMapper: enum togetCode(), andStringtoof(code). - Do not add
static { new _Enum(); }on the enum. - Do not add a conversion method on the JPA Adapter. The full processor is in the enum template.
- Prefer the host
ModelMapperUtilwhen the project already has one.
Errors and responses
- Business failures throw
BizErrorException/BizWarnExceptionwith aResponseTypeInterfacevalue. No ad-hocRuntimeException("not found")and no string-only Biz constructors. - Prefer common
ResponseTypefirst (supported HTTP statuses and shared reasons). Extend with a module enum implementingResponseTypeInterfaceonly for app-specific reasons or message conversion. Do not add new exception classes or Advice handlers by default—add enum values. - Do not duplicate common codes (e.g. generic 404) in a module enum.
- Every Controller method returns
CommonResponse<T>throughCommonResponseUtils.responseSuccess(...). Void writes returnresponseSuccess(). - Exception → HTTP mapping belongs to a global handler (
@RestControllerAdvice), not inside Controllers.
Testing
- Follow tests the target repo already has.
- The Spring template does not include a test slice.
- When the repo uses Mockito, mock the next layer only: Facade tests mock Port, JPA Adapter tests mock Repository.
Prose
문서를 작성하거나 수정할 때는 글쓰기 기준을 확인합니다. 코드 구현 규칙은 이 문서의 나머지 절입니다.
General
- Match the target project's existing style when contributing there; these conventions are the default, not an override.
- Prefer clarity over clever abstractions; a repeated three-line block beats a generic helper nobody can name.
- Keep harness rules separate from project-local rules.
- No credentials, real hostnames, or customer domain terms in anything promoted to the archive.