본문으로 건너뛰기

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 직접 호출 없음)
LayerOwnsMust 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 AdapterSpecs.of(Filter), map / mapAll, BeanUtils.map on update, entity.delete(). CQRS 적용점: optional Read / Command ProviderHTTP, multi-Port 비즈니스 흐름
ProviderAdapter 아래 기술 접근 (RedisProvider, VaultProvider, …)Port 이름에 제품명
RepositoryJpaRepository + empty custom + JpaSpecificationExecutorDerived 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 (호스트명 유지 가능)
모노리포 위치modelapi
모놀리식 위치도메인 폴더 (원셋 facade/)앱의 BFF·feature 패키지
의존자기 Port + DisplayNameResolver도메인 애플리케이션 진입만 (Port 없음)
누가 호출HTTP 도메인 Controller, gRPCGraphQL, 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)호출비고
GraphQLBFF 애플리케이션 진입시나리오 조립이 있을 때. GraphQL을 쓰면 그 진입은 BFF를 거친다
gRPC도메인 애플리케이션 진입 (model)도메인 proto ↔ 도메인 유스케이스
HTTP 도메인 API도메인 애플리케이션 진입 (model)기본. ExampleItem 원셋 → Facade
HTTP BFF APIBFF 애플리케이션 진입화면·시나리오 조립이 필요할 때. 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) 로만 채웁니다. Item findByIds로 대체하지 않습니다. (연관·무거운 컬럼이 끌려옵니다.)
  • 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, @Primary CachePortCacheManager.
  • 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​

ThingConventionExample
Request DTO holder{Domain}Req with inner static classesExampleItemReq.Ids, Filter, Create, Update
Response DTO holder{Domain}Res with inner static classesId, then Name(표시 필드), then Single, then Item
Display name helperDisplayNameResolverapplyCreatedByDisplayNames, findNameMap
Domain application entry기본 Facade (model). 책임 분명할 때만 Manager/Checker/Handler/Processor/ResolverExampleItemFacade, DisplayNameResolver
BFF application entry기본 예 {Feature}BffFacade (api)CheckoutBffFacade (원셋 코드 없음)
Facade / Controller methodsame plain name on bothsearch, save, saveAll, findById, saveById, deleteById, findAll, findByIds, searchName, findAllName, deleteByIds
Port / JPA Adapter methodthe same list, unchanged when an enum is appliedsearch, save, saveAll, findById, saveById, deleteById, findAll, findByIds, searchName, findAllName, deleteByIds
Specification holder{Domain}Specs.of(Filter) onlyExampleItemSpecs.of
Entity table{prefix}_{snake_name}le_example_item
Enum@BizEnum + CodeValue + code / valueEnHttpMethod, 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.
  • Name holds the display field used by DisplayNameResolver / searchName (ExampleItem은 url).
  • Filter has id, then ids, then the column filters, then startAt and endAt.
  • Enum columns stay String on every DTO. Do not store enum.name().
  • 목록 페이징은 PageQuery (DEFAULT_SIZE 20, MAX_SIZE 100, 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 @Transactional at 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 is findById.
  • findByIds and deleteByIds fill Filter.ids and call Specs.of. If ids is null or empty, return without querying.
  • One spec factory: of(Filter). equal per column, in on id for ids, goe / loe on CreatedEntity.createdAt for startAt / endAt.
  • delete() is empty until a status column exists. Do not call repository.delete.
  • A column with a database DEFAULT has no field initializer and no @Builder.Default. @DynamicInsert omits 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.map and mapAll convert DTO ↔ entity and entity → Res.
  • On enum apply, BizEnumProcessor emits _Enum with @Converter(autoApply = true). JPA loads that class. Its static block registers two converters on ModelMapperUtil.modelMapper: enum to getCode(), and String to of(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 ModelMapperUtil when the project already has one.

Errors and responses​

  • Business failures throw BizErrorException / BizWarnException with a ResponseTypeInterface value. No ad-hoc RuntimeException("not found") and no string-only Biz constructors.
  • Prefer common ResponseType first (supported HTTP statuses and shared reasons). Extend with a module enum implementing ResponseTypeInterface only 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> through CommonResponseUtils.responseSuccess(...). Void writes return responseSuccess().
  • 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.