Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions content/topics/java/topic.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ childTopicIds:
- '750d6258-e1be-4813-9487-18c6ba78af0a'
- '57b0dc57-7a64-4c09-9140-2a470748da38'
- '78b29290-d46f-45b2-aaba-c31597ceb6d4'
- 'de9bf772-5146-4995-a438-161b5ad229d2'
relatedTopicIds:
- '0eab5dfb-d4ab-4cf8-a56c-41b4548da56c'
---
16 changes: 16 additions & 0 deletions content/topics/spring-api-errors/sources.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Handle API errors in Spring — authoring sources

Retrieval job: map failures reaching Spring MVC to deliberate HTTP statuses and
a consistent response body. Checked 2026-10-27 against Spring Framework 7 docs.

- [Controller advice](https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-advice.html): bean registration, default controller scope, narrowing selectors, and `@ResponseBody` composition.
- [Exception handlers](https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-exceptionhandler.html): matching exception types and returning `ResponseEntity`.
- [MVC request-body arguments](https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-methods/requestbody.html): Bean Validation failures and default HTTP 400 behavior.
- [Spring MVC default exception resolver](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolver.html): default status mapping for unreadable request bodies.
- [Error responses](https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-ann-rest-exceptions.html): `ProblemDetail`, RFC 9457 fields, the default request path for `instance`, and avoiding disclosure of implementation details.
- [RFC 9110 — status codes](https://www.rfc-editor.org/rfc/rfc9110.html#name-status-codes): 400, 404, 409, and 500 semantics.

The local `spring-boot-api-practice` exercise supplies the concrete names
`ApiError`, `ApiExceptionHandler`, `ProductNotFoundException`, and
`DuplicateSkuException`. The example is intentionally smaller than its handler;
it does not reproduce the exercise's broad `IllegalArgumentException` mapping.
90 changes: 90 additions & 0 deletions content/topics/spring-api-errors/topic.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
---
id: '973352f3-ac82-42a1-a38a-5c09e3946de0'
title: 'Handle API errors in Spring'
status: 'accepted'
iconKey: 'operations'
domains:
- 'java'
- 'http'
kind: 'operations'
childTopicIds: []
relatedTopicIds:
- '31ee0d58-0999-457e-9d7c-5fe20ef9be56'
- 'b97384d3-f986-4850-a6b0-a1c3b893ee86'
---

## Map an exception to a response

```java
record ApiError(String message) {}

@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(ProductNotFoundException.class)
public ResponseEntity<ApiError> handleNotFound(
ProductNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ApiError("Product not found"));
}
}
```

`ProductNotFoundException` is an application exception. This example handles
**only that failure**; add handlers for other failures the API needs to format.

**JSON body:** `{ "message": "Product not found" }`.

| Piece | Role |
| -------------------------- | ------------------------------------- |
| `@RestControllerAdvice` | **Shared handlers** + response bodies |
| `@ExceptionHandler(...)` | Match the **exception type** |
| `ResponseEntity<ApiError>` | **Status, headers, and body** |
| `ApiError` | Your **custom response body type** |

## Choose the status by failure

| Failure | Exception / example | HTTP |
| -------------------- | ----------------------------------- | ------- |
| DTO body validation | `MethodArgumentNotValidException` | **400** |
| JSON/type conversion | `HttpMessageNotReadableException` | **400** |
| Missing product | `ProductNotFoundException` | **404** |
| SKU already in use | `DuplicateSkuException` | **409** |
| Unexpected failure | Programming or infrastructure error | **500** |

These are deliberate API mappings. **Custom exception names do not assign HTTP
statuses.** For DTO failures, get field errors from `ex.getBindingResult()`.

> For unexpected failures, **log the diagnostic details** and return a **safe
> client message**. Avoid forwarding arbitrary exception messages or treating
> every `IllegalArgumentException` as a client error.

## Place and scope the handler

- Put **API-wide error handling** (`ApiExceptionHandler`) and its **response body
type** (`ApiError`) in an `error` package alongside feature packages such as
`product`. Keep product-specific exceptions with `product`.
- Register the advice as a **Spring bean**, usually through component scanning.
The package name does not set its scope: advice applies to **all controllers by
default**; annotation selectors can narrow it.
- **Jobs and calls outside Spring MVC** need their own error handling. Advice
handles exceptions reaching MVC's exception resolution.

## Use Spring's built-in error body

Instead of defining `ApiError`, you can use **`ProblemDetail`**, Spring's type for
a standard HTTP error response:

```json
{
"type": "about:blank",
"title": "Not Found",
"status": 404,
"detail": "Product not found",
"instance": "/products/42"
}
```

**The handler still selects the exception and builds the response.**
`ProblemDetail` supplies the body format.

**`instance`:** Spring MVC uses the current request path when this field is unset.
10 changes: 10 additions & 0 deletions content/topics/spring-bean-validation/sources.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Bean Validation in Spring — authoring sources

References for verifying future edits to `topic.md`. This file is not rendered
in the application.

- [Spring MVC: request body validation](https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-methods/requestbody.html)
- [Spring Boot: service method validation](https://docs.spring.io/spring-boot/reference/io/validation.html)
- [Jakarta: positive numbers and null](https://jakarta.ee/specifications/bean-validation/3.0/apidocs/jakarta/validation/constraints/Positive.html)
- [Hibernate Validator: declaring and executing validation](https://docs.hibernate.org/validator/9.0/reference/en-US/html_single/)
- [Spring: proxy invocation](https://docs.spring.io/spring-framework/reference/core/aop/proxying.html)
74 changes: 74 additions & 0 deletions content/topics/spring-bean-validation/topic.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
---
id: '31ee0d58-0999-457e-9d7c-5fe20ef9be56'
title: 'Bean Validation in Spring'
status: 'accepted'
iconKey: 'operations'
domains:
- 'java'
- 'http'
kind: 'operations'
childTopicIds: []
relatedTopicIds:
- '973352f3-ac82-42a1-a38a-5c09e3946de0'
- '9e290750-ab85-4acb-bca2-88d7ad758cd7'
---

## Validate an incoming body

With `spring-boot-starter-validation` on the classpath:

```java
record CreateItem(
@NotBlank String name,
@NotNull @Positive BigDecimal price) {}

// Spring MVC controller parameter:
// @Valid @RequestBody CreateItem input
```

Spring MVC deserializes the body, then validates its constraints. For this parameter
shape, a failure raises `MethodArgumentNotValidException` and produces **400 by
default**. Customize exception handling for the API's error body.

Malformed JSON fails during deserialization, before Bean Validation; handle that
failure too when providing a consistent error response.

## Choose the constraint

| Annotation | Checks | Rejects `null`? |
| ----------------------------- | ------------------------------------------------- | --------------- |
| `@NotNull` | Value is not `null` | Yes |
| `@NotBlank` | String contains a non-whitespace character | Yes |
| `@Size(min = 1, max = 32)` | String length or container size, inclusive bounds | No |
| `@Positive` | Number is strictly greater than zero | No |
| `@Pattern(regexp = "[A-Z]+")` | String matches the regular expression | No |

**Required positive price:** combine `@NotNull` and `@Positive`.
**Whitespace:** these annotations do not trim input; `@Size` checks the value it
receives.

## What actually runs validation?

| Call path | Activation |
| ------------------------------ | --------------------------------------------- |
| MVC request body | `@Valid @RequestBody` |
| Spring bean method | `@Validated` class + `@Valid` object argument |
| Explicit Java call | `Validator.validate(object)` |
| Ordinary `new CreateItem(...)` | No automatic annotation checks |

> **Constraint annotations declare rules; validation needs an execution path.**
> A constructor needs explicit checking code to reject invalid arguments on an
> ordinary `new` call.

For explicit validation, a non-empty result means the object failed its constraints;
`validate` itself returns violations rather than throwing for invalid field values:

```java
// validator is an injected jakarta.validation.Validator.
var violations = validator.validate(input);
```

- Spring method validation requires a call **through the proxy**; `this` calls bypass it.
- For nested objects, `@Valid` cascades into their constraints; add `@NotNull` if
the nested object itself is required.
- Bean Validation failures outside MVC do not automatically mean HTTP 400.
31 changes: 31 additions & 0 deletions content/topics/spring-boot-create-run/sources.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Create and run a Spring Boot app — authoring sources

Retrieval job: recover the generation choices, local run commands, and controller
syntax for creating and retrieving a resource. Checked 2026-10-28.

- [IntelliJ Spring Boot project wizard](https://www.jetbrains.com/help/idea/spring-initializr-project-wizard.html): menu path, shared project settings, dependencies, and default Initializr service.
- [Spring Initializr reference](https://docs.spring.io/initializr/docs/current/reference/html/): project-generation service and metadata.
- [Spring Initializr service](https://start.spring.io/): browser generator. The verification fixture was generated by this service with Boot 4.1.2, Java 21, Maven, `ProductsApplication`, and Web MVC/Validation dependencies.
- [Run a Spring Boot application](https://docs.spring.io/spring-boot/reference/using/running-your-application.html): IDE, Maven plugin, executable JAR, and duplicate-port behavior.
- [Actuator endpoints](https://docs.spring.io/spring-boot/reference/actuator/endpoints.html): built-in health endpoint, default HTTP exposure, and health indicator aggregation.
- [Managed dependency coordinates](https://docs.spring.io/spring-boot/appendix/dependency-versions/coordinates.html): managed `org.springframework.boot:spring-boot-starter-actuator` dependency. Also present in the local exercise's Maven configuration.
- [IntelliJ Spring application example](https://www.jetbrains.com/help/idea/your-first-spring-application.html): generated main class, running it, and default HTTP port 8080.
- [Structure Spring Boot code](https://docs.spring.io/spring-boot/reference/using/structuring-your-code.html): root application package and default scanning.
- [MVC request mappings](https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-requestmapping.html): REST controller, HTTP method mappings, and path variables.
- [MVC request body](https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-methods/requestbody.html): JSON deserialization and `@Valid`.
- [ResponseEntity API](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html): `created(URI)` sets HTTP 201 and the Location header.

The controller and record shapes are adapted from the local
`spring-boot-api-practice` exercise. The Topic deliberately shows only the web
boundary, assuming the exercise's service contract and Product getters; it is
not a complete standalone CRUD application. Imports are omitted from snippets.

The authored controller and records were compiled in the generated project with
the exercise's service/repository/model, adapting packages and adding imports.
Both the packaged JAR and Maven development run returned POST 201 with Location
and GET 200 with the matching product JSON. Verified on JDK 25 targeting Java 21.

The Actuator dependency was also checked in a fresh generated app with no
controllers or custom exposure settings. `/actuator/health` returned HTTP 200
with `status: UP` and additional health-group fields; the Topic intentionally
checks the status rather than prescribing an exact response object.
128 changes: 128 additions & 0 deletions content/topics/spring-boot-create-run/topic.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
---
id: '2eae671e-54ad-4afa-b85f-26415d0cea59'
title: 'Create and run a Spring Boot app'
status: 'accepted'
iconKey: 'operations'
domains:
- 'java'
- 'http'
kind: 'operations'
childTopicIds: []
relatedTopicIds:
- '31ee0d58-0999-457e-9d7c-5fe20ef9be56'
- '973352f3-ac82-42a1-a38a-5c09e3946de0'
---

## Create the skeleton

| Method | Generate the project |
| -------------- | ---------------------------------------------------------- |
| **IntelliJ** | File → New → Project → **Spring Boot** |
| **Initializr** | [start.spring.io](https://start.spring.io/) → **Generate** |

IntelliJ's wizard uses **Spring Initializr**. For these examples, choose **Java 21 ·
Maven · JAR**, a released Boot version, and dependencies **Spring Web + Validation**.

**Name:** `Products` · **Artifact:** `products` · **Group:** `com.example` ·
**Package:** `com.example.products`.

For a downloaded ZIP, extract it and open the folder containing `pom.xml` as a
Maven project in IntelliJ.

## Run the app

Run terminal commands from **the project root** (`products/`, containing `pom.xml`
and `mvnw`).

| From | Start the application |
| ------------ | ---------------------------------------------- |
| **IntelliJ** | Run the generated `ProductsApplication.main()` |
| **Terminal** | `./mvnw spring-boot:run` |

### Check health with Actuator

Select **Spring Boot Actuator** in Initializr, or add this dependency inside
`pom.xml`'s `<dependencies>`:

```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
```

**Run or restart** the app, then check:

```bash
curl http://localhost:8080/actuator/health
```

**Healthy response:** includes `"status": "UP"`; additional fields may appear.

Health is **exposed by default**; **no custom controller is required**.
`UP` reflects the configured health checks; it does not verify product endpoints.

### Run a packaged JAR

```bash
./mvnw package
java -jar target/products-0.0.1-SNAPSHOT.jar
```

`spring-boot:run` runs from the project; **`java -jar` runs the built artifact**.
Rebuild the JAR after changing source code.

## Create and fetch a product

| Request | Successful response |
| -------------------- | ------------------------------------------- |
| `POST /products` | **201 Created** + `Location` + product body |
| `GET /products/{id}` | **200 OK** + product body |

> Keep the controller and service **in or below the application's root package**
> (`com.example.products`) so default component scanning finds them.

### Request and response records

```java
record CreateProductRequest(
@NotBlank String sku,
@NotBlank String name,
@NotNull @Positive BigDecimal price) {}

record ProductResponse(
UUID id, String sku, String name, BigDecimal price) {}
```

### Controller

```java
@RestController
@RequestMapping("/products")
public class ProductController {
private final ProductService service;

public ProductController(ProductService service) {
this.service = service;
}

@PostMapping
public ResponseEntity<ProductResponse> create(
@Valid @RequestBody CreateProductRequest input) {
Product product = service.create(input);
URI location = URI.create("/products/" + product.getId());
return ResponseEntity.created(location)
.body(toResponse(product));
}

@GetMapping("/{id}")
public ProductResponse get(@PathVariable("id") UUID id) {
return toResponse(service.get(id));
}

private ProductResponse toResponse(Product product) {
return new ProductResponse(product.getId(), product.getSku(),
product.getName(), product.getPrice());
}
}
```
18 changes: 18 additions & 0 deletions content/topics/spring-boot/sources.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Spring and Spring Boot — authoring sources

References for verifying `topic.md`; not rendered in the application. Checked
2026-10-27. The Topic compares Spring with and without Boot, rather than specific
Framework or Boot major versions.

- [Spring Framework overview](https://docs.spring.io/spring-framework/reference/overview.html): the Spring family, core container, optional modules, and web/non-web application scenarios.
- [Spring Framework project](https://spring.io/projects/spring-framework/): infrastructure, dependency injection, transactions, data-access integration, and testing support.
- [Spring MVC](https://docs.spring.io/spring-framework/reference/web/webmvc.html): Servlet-based web framework within Spring Framework.
- [Spring Data](https://spring.io/projects/spring-data/): separate project family providing repository and data-access abstractions.
- [Spring Security](https://spring.io/projects/spring-security/): separate project providing authentication and authorization.
- [Spring Integration](https://spring.io/projects/spring-integration/): message flows, enterprise integration patterns, and adapters for external systems.
- [Spring Batch](https://spring.io/projects/spring-batch/): batch processing, job restart, retry, and Boot integration.
- [Spring Boot project](https://spring.io/projects/spring-boot/): starters, auto-configuration, embedded servers, executable applications, and production features.
- [Boot dependency management and starters](https://docs.spring.io/spring-boot/reference/using/build-systems.html): managed dependency versions and dependency descriptors.
- [Boot auto-configuration](https://docs.spring.io/spring-boot/reference/using/auto-configuration.html): conditional defaults and replacing them with application configuration.
- [Spring Java configuration](https://docs.spring.io/spring-framework/reference/core/beans/java.html): annotation-based configuration is available independently of Boot.
- [Boot traditional deployment](https://docs.spring.io/spring-boot/how-to/deployment/traditional-deployment.html): Servlet applications can use external-container WAR deployment as an alternative to an embedded server.
Loading
Loading