Every Spring Boot service we open ends up needing the same handful of patterns. Rather than keep re-deriving them, here they are. All examples are Kotlin but translate cleanly to Java.
1. A single @RestControllerAdvice for errors
@RestControllerAdvice
class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException::class)
fun onValidation(ex: MethodArgumentNotValidException): ResponseEntity<ApiError> {
val fields = ex.bindingResult.fieldErrors.associate {
it.field to (it.defaultMessage ?: "invalid")
}
return ResponseEntity
.badRequest()
.body(ApiError("validation_failed", "Validation failed", fields))
}
@ExceptionHandler(NoSuchElementException::class)
fun onNotFound(ex: NoSuchElementException): ResponseEntity<ApiError> =
ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(ApiError("not_found", ex.message ?: "Not found"))
@ExceptionHandler(Exception::class)
fun onOther(ex: Exception): ResponseEntity<ApiError> {
log.error("unhandled exception", ex)
return ResponseEntity
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ApiError("internal_error", "Something broke"))
}
companion object { private val log = LoggerFactory.getLogger(GlobalExceptionHandler::class.java) }
}
data class ApiError(
val code: String,
val message: String,
val fields: Map<String, String>? = null
)
One place for all error shaping. Every endpoint ships the same JSON format. Docs.
2. @Valid on every request body, always
data class CreatePostRequest(
@field:NotBlank @field:Size(max = 120) val title: String,
@field:NotBlank @field:Size(max = 320) val excerpt: String,
@field:Pattern(regexp = "^(AI|Tooling|Gizmos|Vankode)$") val category: String
)
@PostMapping("/posts")
fun create(@Valid @RequestBody body: CreatePostRequest): PostResponse =
postService.create(body)
Paired with the handler above, any bad request automatically returns a 400 with field-level messages. Never write validation in the controller again.
3. A single pagination response type
data class Page<T>(
val items: List<T>,
val total: Long,
val page: Int,
val size: Int
) {
val totalPages: Int get() = ((total + size - 1) / size).toInt()
companion object {
fun <T> of(source: org.springframework.data.domain.Page<T>) = Page(
items = source.content,
total = source.totalElements,
page = source.number,
size = source.size
)
}
}
Every list endpoint returns the same shape. The frontend writes one pagination helper and reuses it everywhere.
4. @ConfigurationProperties instead of @Value
Before:
@Value("\${log4j.feed.pageSize:10}") private lateinit var pageSize: String
After:
@ConfigurationProperties(prefix = "log4j")
data class Log4jProperties(
val feed: Feed = Feed()
) {
data class Feed(val pageSize: Int = 10)
}
Registered once in a @Configuration:
@Configuration
@EnableConfigurationProperties(Log4jProperties::class)
class Log4jConfig
Now pageSize is an Int, not a String you re-parse. Autocomplete works. Tests are trivial. Docs.
5. Keep controllers thin
@RestController
@RequestMapping("/api/posts")
class PostController(private val posts: PostService) {
@GetMapping fun list(@ParameterObject q: PostQuery): Page<PostResponse> =
posts.list(q)
@GetMapping("/{id}") fun get(@PathVariable id: UUID): PostResponse =
posts.get(id)
@PostMapping fun create(@Valid @RequestBody body: CreatePostRequest): PostResponse =
posts.create(body)
@PutMapping("/{id}")
fun update(@PathVariable id: UUID, @Valid @RequestBody body: UpdatePostRequest): PostResponse =
posts.update(id, body)
@DeleteMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT)
fun delete(@PathVariable id: UUID) {
posts.delete(id)
}
}
Every controller method is one line. Anything longer lives in the service. This is the single biggest readability win you can apply.
6. OpenAPI from code, not hand-written
Add springdoc-openapi:
// build.gradle.kts
implementation("org.springdoc:springdoc-openapi-starter-webmvc-ui:2.7.0")
Auto-mounted at /swagger-ui.html. The schema is accurate because it is derived. Hand-written OpenAPI always rots.
That is five lines of build.gradle and a free API doc that stays in sync.
What we avoid
@Autowiredfield injection. Constructor injection is non-negotiable.- JPA entities as request/response bodies. Always separate types.
- Controller methods with more than one line of logic.
- Custom
ObjectMapperconfiguration spread across multiple files — keep it in oneJacksonConfig.
If your Spring Boot app looks like this, you will get a lot of productive work done before you have to think hard about it.


