⚙ Engineer view
Implementation detail, patterns, dependencies, gotchas · Software Engineer, Tech Lead
⚡ Agent trace · 13 steps · $0.0422 · click to expand
search_claims(query='main entry point application startup', max_results=25) →
search_claims(query='module structure package overview', max_results=25) →
search_claims(max_results=30, query='Article aggregate root domain model') →
search_claims(max_results=30, query='controller REST endpoint request mapping') →
get_file_claims(file_path='src/main/java/io/spring/core/article/Article.java') →
get_file_claims(file_path='src/main/java/io/spring/application/ArticleQueryService.java') →
get_file_claims(file_path='src/main/java/io/spring/api/security/JwtTokenFilter.java') →
get_file_claims(file_path='src/main/java/io/spring/api/security/WebSecurityConfig.java') →
read_source_file(file_path='src/main/java/io/spring/api/security/WebSecurityConfig.java', start_line=35) →
read_source_file(file_path='src/main/java/io/spring/api/security/JwtTokenFilter.java', start_line=18) →
get_file_claims(file_path='src/main/java/io/spring/graphql/ArticleDatafetcher.java') →
get_file_claims(file_path='src/main/java/io/spring/MyBatisConfig.java') →
get_file_claims(file_path='src/main/java/io/spring/application/CursorPager.java') →
search_claims(max_results=25, query='MyBatis XML mapper SQL query file') →
search_claims(max_results=25, query='application.properties datasource schema migration flyway') →
get_file_claims(file_path='src/main/java/io/spring/infrastructure/repository/MyBatisArticleRepository.java') →
get_dependencies(file_path='src/main/java/io/spring/application/ArticleQueryService.java') →
get_dependencies(file_path='src/main/java/io/spring/core/article/Article.java') →
get_file_claims(file_path='src/main/java/io/spring/core/service/AuthorizationService.java') →
get_file_claims(file_path='src/main/java/io/spring/application/user/UserService.java') →
read_source_file(end_line=106, file_path='src/main/java/io/spring/application/user/UserService.java') →
get_file_claims(file_path='src/main/java/io/spring/graphql/ArticleMutation.java') →
get_file_claims(file_path='src/main/java/io/spring/api/security/SecurityUtil.java') →
search_claims(max_results=25, query='exception handler controller advice validation error')
Engineer's Guide
This is a Spring Boot implementation of the RealWorld ("Conduit") API — a Medium-clone backend. It exposes two parallel API surfaces (REST + GraphQL/DGS) over a shared application core, with a CQRS-style split between command services (write via domain repositories) and query services (read via MyBatis read services).
Module Map
| Module / File | Role | Key Responsibilities | In-Degree |
|---|---|---|---|
core/article/Article.java |
Domain aggregate root | Article entity, slug generation, conditional update, UUID id | Very high (~25 importers incl. all GraphQL + REST + tests) |
application/ArticleQueryService.java |
Query service (read side) | Article listing, cursor pagination, "extra info" enrichment (favorited/favoritesCount/following) | High (10 importers: 4 REST controllers, GraphQL, validator, tests) |
api/*Api.java (ArticleApi, ArticlesApi, CommentsApi, ProfileApi, UsersApi, CurrentUserApi, TagsApi, ArticleFavoriteApi) |
REST controllers | HTTP endpoints, request binding, auth principal injection | — |
graphql/*Datafetcher.java, *Mutation.java |
GraphQL (DGS) layer | Queries/mutations, local-context batching, cursor connections | — |
application/article/ArticleCommandService.java |
Command service (write side) | create/update article via ArticleRepository |
— |
application/user/UserService.java |
User command service + validation | Registration, update, custom constraint validators | — |
core/service/AuthorizationService.java |
Domain policy | Static canWriteArticle / canWriteComment checks |
— |
infrastructure/repository/MyBatis*Repository.java |
Repository impls | Persist domain objects via MyBatis mappers | — |
infrastructure/mybatis/readservice/* |
Read-side mappers | Query DTOs (ArticleData, UserData, etc.) via XML SQL |
— |
infrastructure/mybatis/mapper/* |
Write-side mappers | Insert/update/delete domain entities | — |
api/security/* |
Security | JWT filter, WebSecurityConfig, SecurityUtil |
— |
api/exception/*, graphql/exception/* |
Error handling | REST @ControllerAdvice + GraphQL exception handler |
— |
MyBatisConfig.java, JacksonCustomizations.java |
Config | Transaction management; Jackson module registration | — |
Design Patterns in Use
1. CQRS (Command/Query separation) — applied consistently.
- Write side: ArticleCommandService.createArticle / updateArticle operate on the Article aggregate and persist via ArticleRepository (application/article/ArticleCommandService.java:18-37).
- Read side: ArticleQueryService never touches the aggregate repository — it reads DTOs (ArticleData) through MyBatis read services (ArticleQueryService.java:30-123).
- The two mapper families are deliberately separate: infrastructure/mybatis/mapper/* (writes, domain entities) vs infrastructure/mybatis/readservice/* (reads, DTOs). Note the read services are named *ReadService but are actually @Mapper interfaces (ArticleReadService.java:10, UserReadService.java:7).
2. Repository pattern. ArticleRepository is a domain interface (core/article/ArticleRepository.java:5-14); MyBatisArticleRepository implements it (MyBatisArticleRepository.java:11-57). save() does an upsert-by-existence-check (MyBatisArticleRepository.java:19-27).
3. DTO / Data Mapper. ArticleData, UserData, CommentData, ArticleFavoriteCount are read-model DTOs in application/data/, populated by MyBatis XML.
4. Cursor pagination via Node interface. ArticleData implements Node (ArticleData.java:11-33) exposing a getCursor(); CursorPager<T extends Node> wraps results with hasNext/hasPrevious and start/end cursors (CursorPager.java:6-44). Direction is PREV/NEXT (CursorPager.java:40-43).
5. GraphQL DataLoader-style batching via local context. Datafetchers stash the fetched object in DataFetcherResult local context keyed by slug/id, and child field resolvers read from it instead of re-querying (ArticleDatafetcher.java:42-86, :300-319; CommentDatafetcher.java:35-48, :50-100).
6. Custom Bean Validation constraints. @DuplicatedEmailConstraint, @DuplicatedUsernameConstraint, @DuplicatedArticleConstraint, @UpdateUserConstraint with ConstraintValidator implementations (UserService.java:59-106, DuplicatedArticleConstraint.java:14-20).
7. Static domain policy. AuthorizationService is stateless with two static methods (AuthorizationService.java:7-15).
Critical Implementation Details
Article slug generation is lossy and non-unique. Article.toSlug lowercases the title and replaces a regex of punctuation/whitespace/CJK punctuation with hyphens (Article.java:67-69). Two articles with the same title produce the same slug — uniqueness is enforced only by a DB constraint, surfaced as DuplicatedArticleConstraint ("article name exists", DuplicatedArticleConstraint.java:15). Slugs are computed at construction, not on update.
Article.update is a partial update. It only overwrites title/description/body when the new value is non-empty (via Util.isEmpty) and bumps updatedAt on each change (Article.java:51-65). Sending an empty string in an update request silently leaves the old value.
Article equality is by id only — @EqualsAndHashCode(of = {"id"}) (Article.java:11-13). This matters in UpdateUserValidator, which compares users by equals to decide "is this the same user" (UserService.java:80-86).
Read-side enrichment is N+1-ish by design. ArticleQueryService.fillExtraInfo makes separate batched calls to setFavoriteCount, setIsFavorite, setIsFollowingAuthor (ArticleQueryService.java:133-183). For a single article it calls each read service individually (:175-183); for lists it batches by ID set. Any new list endpoint must call fillExtraInfo or the favorited/favoritesCount/following fields will be null/false.
Cursor pagination reverses results for PREV. findRecentArticlesWithCursor trims to limit, then reverses the list if direction != NEXT before fetching full articles (ArticleQueryService.java:54-78). CursorPager then sets previous vs next based on direction and hasExtra (CursorPager.java:40-43). Getting direction wrong silently returns pages in the wrong order.
GraphQL requires exactly one of first/last. getFeed throws IllegalArgumentException if both are null (ArticleDatafetcher.java:42-86).
JWT filter is permissive and stateless. JwtTokenFilter extracts the token by splitting the Authorization header on space and taking index 1 (JwtTokenFilter.java:50-61); it only sets authentication if the context is currently null (:32), and always calls filterChain.doFilter (:47) — it never rejects a request itself. Rejection is delegated to WebSecurityConfig's anyRequest().authenticated() (WebSecurityConfig.java:61-62). The token carries only a subject (user id); authorities are always empty (JwtTokenFilter.java:37-39).
Security matcher ordering is load-bearing. GET /articles/feed is matched as authenticated() before the broader GET /articles/** permitAll rule (WebSecurityConfig.java:55-60). Reordering these lines would make the feed public. CSRF is disabled and sessions are STATELESS (:38-46).
Two independent error-handling stacks. REST uses CustomizeExceptionHandler where all handlers return HTTP 422 (CustomizeExceptionHandler.java:27-99) — except @ResponseStatus-annotated exceptions (ResourceNotFoundException → 404, NoAuthorizationException → 403). GraphQL uses GraphQLCustomizeExceptionHandler, mapping ConstraintViolationException → BAD_REQUEST and InvalidAuthenticationException → UNAUTHENTICATED (GraphQLCustomizeExceptionHandler.java:30-68). The same logical error returns different status codes across the two APIs.
JSON root wrapping is annotation-driven. Request/response params use @JsonRootName("article") / @JsonRootName("user") / @JsonRootName("errors") (UpdateArticleParam.java:14, RegisterParam.java:15, ErrorResource.java:15), enabled by JacksonCustomizations (JacksonCustomizations.java:17-20). Controllers also manually wrap responses in a HashMap with key "article" (ArticlesApi.java:28-38) — so wrapping happens in two places.
Entry Points — Start Here
RealWorldApplication.java:9-11— themain/SpringApplication.runbootstrap. Trivial but the true start.api/security/WebSecurityConfig.java:35-65— defines the entire public/private surface of the API. Read this first to understand what's reachable without auth.application/ArticleQueryService.java:23-184— the heart of the read side; every list/detail endpoint funnels through it. UnderstandfillExtraInfoand the cursor methods here.core/article/Article.java:11-69— the aggregate root; slug generation and partial-update semantics live here and affect every write path.graphql/ArticleDatafetcher.java:35-384— the largest, most intricate file; shows the local-context batching pattern and cursor→connection mapping. Read after the REST side to see the parallel implementation.
Known Gotchas
-
UpdateUserValidatoruses field@Autowiredbut is not a Spring bean. It's a package-private class instantiated by the Bean Validation provider (UserService.java:70-72). Field injection into a validator created by Hibernate Validator is unreliable — this is flagged as a limitation (UserService.java:70-106). If email/username uniqueness checks silently stop working, look here first. -
getTokenStringcan returnOptional.ofNullable(null).split[1]is wrapped inOptional.ofNullable(JwtTokenFilter.java:58), so a malformed header like"Bearer "yields an empty Optional downstream — safe, but thesplit.length < 2guard (:55) is the only real protection. Headers with extra spaces produce wrong token slices. -
AuthorizationServicehas no null checks.canWriteArticle/canWriteCommentdereferencegetId()/getUserId()directly (AuthorizationService.java:8-14); a null user or article throws NPE rather than returning false. -
canWriteCommentallows the article author OR the comment author (AuthorizationService.java:12-14) — a subtle rule that's easy to get wrong when adding comment moderation. -
MyBatisArticleRepository.createNewdoes tag find-or-insert per tag (MyBatisArticleRepository.java:29-41) inside a@Transactional save()(:19-27). Concurrent article creation with the same new tag can race on tag insertion. -
TagsApihas no validation or error handling (TagsApi.java:17-25), andTagsQueryService.allTags()lets exceptions propagate uncaught (TagsQueryService.java:13-15). -
Mapper interfaces contain no SQL.
CommentMapper,UserReadService, etc. are pure@Mapperinterfaces (CommentMapper.java:7-14,UserReadService.java:7-13); the actual SQL lives in XML resources. A method rename in Java without a matching XML change fails only at runtime. -
MyBatisConfigis empty except@EnableTransactionManagement(MyBatisConfig.java:6-8) — datasource/mapper-scan config lives elsewhere (properties/auto-config). Don't expect to find SQL session config here. -
Tests use a real database.
DbTestBasesets@AutoConfigureTestDatabase(replace = Replace.NONE)(DbTestBase.java:9), so integration tests require a live DB — they will fail in a bare CI without one.