Scope
Swagger UI turns your API’s OpenAPI description into an interactive page where developers and testers can read every endpoint, its parameters and responses, and try it out from the browser. In Spring Boot, the standard way to get both the OpenAPI document and the UI is springdoc-openapi: it inspects your controllers at runtime, so the documentation is generated from the code and cannot drift away from it.
We still run Spring Boot 2.7 applications (on application servers that cannot host Spring Boot 3) next to Spring Boot 3 and 4 ones, and the two generations differ in more than the dependency line: package names, the Spring Security API, the error body and the page format all change. So this post shows two implementations. Most of the setup is shared; wherever it differs you will find a Spring Boot 2.7 block and a Spring Boot 3 and 4 block. Pick yours and skip the other.
Tested with: Spring Boot 2.7 with springdoc-openapi 1.7 (javax, Spring Security 5.7, Spring Data 2.7); Spring Boot 3.2 with springdoc 2.3 and Spring Boot 4.1 with springdoc 3.0.3 (jakarta, Spring Security 6 / 7). ProblemDetail and the VIA_DTO page format appear only in the Spring Boot 3 and 4 blocks because they do not exist on 2.7; VIA_DTO needs Spring Boot 3.3 or later.
Which version goes with which
| Spring Boot 2.7 | Spring Boot 3 | Spring Boot 4 | |
|---|---|---|---|
| springdoc-openapi | 1.x (last release 1.8.0) | 2.x (2.3 for Boot 3.2 … 2.8 for Boot 3.4 / 3.5) | 3.x |
| Artifact | springdoc-openapi-ui | springdoc-openapi-starter-webmvc-ui | springdoc-openapi-starter-webmvc-ui |
| Servlet / validation API | javax.* | jakarta.* | jakarta.* |
| Default OpenAPI output | 3.0 | 3.0 up to springdoc 2.7, 3.1 from 2.8 | 3.1 |
@ParameterObject package | org.springdoc.api.annotations | org.springdoc.core.annotations | org.springdoc.core.annotations |
springdoc is not managed by Spring Boot, so the version is yours to choose. Check the compatibility notes on springdoc.org and the springdoc changelog whenever you upgrade Spring Boot.
Swagger configuration
Add the dependency
Spring Boot 2.7
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.7.0</version>
</dependency>
One dependency. springdoc-openapi-ui already brings springdoc-openapi-common; do not declare that one as well.
Spring Boot 3 and 4
<!-- Spring Boot 3.4 / 3.5: springdoc 2.8.x. Spring Boot 4: springdoc 3.x (we run 3.0.3 on 4.1) -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>3.0.3</version>
</dependency>
Either way, the OpenAPI document is served at /v3/api-docs and the UI at /swagger-ui.html (which redirects to /swagger-ui/index.html).
Describe the API, and make Authorize work (both versions)
Define an OpenAPI bean with the API’s metadata. If the API is secured with bearer tokens (OAuth 2.0 / JWT), declare the scheme here too: Swagger UI then shows an Authorize button, and every Try it out call carries the token. The model classes (io.swagger.v3.oas.models.*) have the same package names in both generations, so this bean is identical.
@Configuration
public class OpenApiConfig {
private static final String BEARER = "bearer-jwt";
@Bean
public OpenAPI openAPI(BuildProperties buildProperties) {
return new OpenAPI()
.info(new Info()
.title("Orders API")
.description("Create, search and track customer orders.")
.version(buildProperties.getVersion()))
.addSecurityItem(new SecurityRequirement().addList(BEARER))
.components(new Components()
.addSecuritySchemes(BEARER, new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")));
}
}
Info also has a summary field, but it belongs to OpenAPI 3.1. springdoc 2.8 and later (so every Spring Boot 4 setup) produce 3.1 by default and show it; springdoc 1.x and 2.0–2.7 produce 3.0 and drop it, unless you set springdoc.api-docs.version=openapi_3_1. If you are on 2.7, put the text in description.
BuildProperties (the version from your pom.xml) exists only if the Spring Boot Maven plugin writes the build information:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>build-info</goal>
</goals>
</execution>
</executions>
</plugin>
Let the documentation through Spring Security
If the application uses Spring Security, permit the UI and the OpenAPI document explicitly. The paths are the same; the matcher API is not.
Spring Boot 2.7 (Spring Security 5.7)
http.authorizeHttpRequests(auth -> auth
.antMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html").permitAll()
.anyRequest().authenticated());
Spring Boot 3 and 4 (Spring Security 6 / 7)
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html").permitAll()
.anyRequest().authenticated());
antMatchers was removed in Spring Security 6, so the 2.7 line does not compile after an upgrade — which is at least a loud failure. The page itself is public; the API calls made from it still need a valid token, entered through Authorize.
Behind a reverse proxy (both versions)
When the application runs behind a reverse proxy that changes the path or the scheme (for example https://example.com/orders-api/ in front of http://app:8080/), Swagger UI must build its URLs from what the browser sees, not from what the application sees. The proxy passes that information in the X-Forwarded-* headers (X-Forwarded-Proto, X-Forwarded-Host, X-Forwarded-Prefix), and Spring Boot applies them when you ask it to:
# Apply X-Forwarded-* headers, so springdoc generates the URLs the browser sees
server.forward-headers-strategy=framework
With framework, Spring Boot registers Spring’s ForwardedHeaderFilter for you — there is no need to declare it as a bean as well. (native lets the embedded server handle the headers instead; we use framework because Spring’s filter also applies X-Forwarded-Prefix, the header that carries the path — check your server’s documentation before relying on native for that.) The property and its behaviour are the same on 2.7, 3 and 4.
Only enable this when the application is reachable exclusively through a proxy that sets or overwrites these headers. Otherwise a client can send its own X-Forwarded-Host and make the application generate links to a host of its choosing.
Development and production settings (both versions)
The defaults are fine for development. In production, decide explicitly whether the documentation should be served at all, and whether Try it out should be available. The property names are the same in springdoc 1.x, 2.x and 3.x:
# application.properties — defaults
springdoc.api-docs.enabled=true
springdoc.swagger-ui.enabled=true
# application-prod.properties — production override
springdoc.api-docs.enabled=false
springdoc.swagger-ui.enabled=false
If you keep the UI in production but want it read-only, an empty list of submit methods removes the Try it out button:
springdoc.swagger-ui.supported-submit-methods=
Annotate the controllers
@Tag groups the operations of a controller:
@RestController
@RequestMapping("/orders")
@Tag(name = "Orders", description = "Create, search and track customer orders")
public class OrderController {
@Operation, @Parameter and @ApiResponse describe each endpoint. The method below is the same in both generations; only the import of @ParameterObject changes:
Spring Boot 2.7 (springdoc 1.x)
import org.springdoc.api.annotations.ParameterObject;
Spring Boot 3 and 4 (springdoc 2.x / 3.x)
import org.springdoc.core.annotations.ParameterObject;
@Operation(summary = "Search orders")
@ApiResponse(responseCode = "200", description = "A page of matching orders")
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public OrderPage searchOrders(
@Parameter(description = "Order statuses to include",
array = @ArraySchema(schema = @Schema(type = "string", allowableValues = {"NEW", "PAID", "SHIPPED"})))
@RequestParam(value = "status", required = false) List<String> statuses,
@Parameter(description = "Customer id")
@RequestParam(value = "customerId", required = false) Long customerId,
@Parameter(description = "Created on or after this date (yyyy-MM-dd)")
@RequestParam(value = "createdFrom", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate createdFrom,
@Parameter(description = "Created on or before this date (yyyy-MM-dd)")
@RequestParam(value = "createdTo", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate createdTo,
@ParameterObject
@PageableDefault(size = 50) @SortDefault(sort = "createdAt", direction = Sort.Direction.DESC)
Pageable pageable) {
return OrderPage.of(orderService.search(statuses, customerId, createdFrom, createdTo, pageable));
}
A few things worth noticing:
@ParameterObjectdocuments thePageableas its three real query parameters (page,size,sort) instead of a JSON body. When you upgrade from 2.7, the old import no longer exists — fix the package, not the annotation.allowableValuesturns the parameter into a drop-down in the UI;array = @ArraySchema(...)is what makes a list parameter a multi-select.- Typed parameters (
LocalDate,Long) are documented with their real types and validated by Spring; withStringthey would be neither. - There is no hand-written 401 handling: Spring Security answers unauthenticated calls before the controller runs.
- The method returns
OrderPage, a page DTO of our own, rather thanPage<OrderSummary>— see the note on page responses below for why, and for the Spring Boot 3.3+ alternative.
Document error responses once
Repeating @ApiResponse(responseCode = "400" …), 401, 403 and 500 on every method is noise, and it drifts. springdoc reads your @RestControllerAdvice: every @ExceptionHandler annotated with @ResponseStatus is added to the responses of every operation, with its body type. What differs between the generations is the body.
Spring Boot 2.7: your own error class
ProblemDetail arrived in Spring Framework 6, so on 2.7 the body is a class of your own. Keep it small and stable — clients code against it:
public class ApiError {
private final String code;
private final String message;
public ApiError(String code, String message) {
this.code = code;
this.message = message;
}
public String getCode() { return code; }
public String getMessage() { return message; }
}
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ApiError invalidRequest(MethodArgumentNotValidException ex) {
return new ApiError("INVALID_REQUEST", "The request is not valid.");
}
}
Spring Boot 3 and 4: ProblemDetail (RFC 9457)
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ProblemDetail invalidRequest(MethodArgumentNotValidException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "The request is not valid.");
}
}
In both cases the message is a fixed text, not the rejected value: handlers like this one usually log what they return, and a value from the request has no business in a log line. Keep @ApiResponse on a method only for what is specific to it (a 404 for a lookup by id, a 409 for a conflict).
A note on Page responses
Returning Page<T> directly serialises Spring Data’s PageImpl, whose JSON shape is an implementation detail — and that shape is what Swagger UI then documents as your contract.
Spring Boot 2.7: return your own page DTO
Spring Data 2.7 has no switch for this, so map the page yourself. A handful of fields is all a client needs:
public class OrderPage {
private final List<OrderSummary> content;
private final int page;
private final int size;
private final long totalElements;
private final int totalPages;
private OrderPage(List<OrderSummary> content, int page, int size, long totalElements, int totalPages) {
this.content = content;
this.page = page;
this.size = size;
this.totalElements = totalElements;
this.totalPages = totalPages;
}
public static OrderPage of(Page<OrderSummary> p) {
return new OrderPage(p.getContent(), p.getNumber(), p.getSize(), p.getTotalElements(), p.getTotalPages());
}
// getters
}
Spring Boot 3.3 and later: the stable DTO shape
From Spring Data 3.3 (Spring Boot 3.3) onwards, serialising a PageImpl logs a warning, and one annotation switches every Page response to a stable DTO shape:
@EnableSpringDataWebSupport(pageSerializationMode = EnableSpringDataWebSupport.PageSerializationMode.VIA_DTO)
With that in place a controller may return Page<OrderSummary> again. On Spring Boot 3.0–3.2 the annotation attribute does not exist; use your own page DTO as on 2.7. Either way the schema in Swagger UI is then one you control.
Pitfalls
- Mixing generations. A
springdoc-openapi-ui1.x dependency on Spring Boot 3, or a starter 2.x on 2.7, fails at startup with class-not-found errors onjavax/jakartatypes. Match the table above. - Upgrade breaks the imports. Moving from 2.7 to 3 changes the
@ParameterObjectpackage and removesantMatchers; both are compile errors, which is the good case. The quiet change is the default OpenAPI output moving to 3.1 from springdoc 2.8 — a client generator pinned to 3.0 may needspringdoc.api-docs.version=openapi_3_0. - Duplicate forwarded-header handling.
server.forward-headers-strategy=frameworkand aForwardedHeaderFilterbean register the filter twice. Use the property. - Forwarded headers without a proxy. Trusting
X-Forwarded-*on an application clients can reach directly lets them choose the host your links point to. - Swagger UI loads but shows “Failed to load API definition”. Usually the security configuration blocks
/v3/api-docs/**while allowing/swagger-ui/**, or the proxy prefix is missing so the UI asks for the document at the wrong path. - Authorize button missing. No security scheme in the
OpenAPIbean. - A field that does nothing.
Info.summaryappears only in OpenAPI 3.1 output: by default on springdoc 2.8+ and 3.x, not on 1.x or 2.0–2.7. - Production exposure. Decide per environment; the API description is a map of your attack surface.
Conclusion
springdoc gives you accurate, always-current API documentation for the cost of one dependency and a few annotations, on Spring Boot 2.7 as much as on 3 and 4. The differences between the generations are small but real — the artifact, a package name, the security matchers, the error body and the page format — and the details that make it work in real deployments are the same on both: a security scheme for Authorize, the right forwarded-header strategy behind a proxy, the security exceptions, and an explicit production setting.
Cheers!
Related sources
- springdoc-openapi documentation (v2 / v3)
- springdoc-openapi v1 documentation (Spring Boot 2)
- springdoc-openapi properties
- Spring Boot: running behind a front-end proxy server
- Swagger UI configuration
- OpenAPI Specification
- A Spring Boot resource server on Keycloak, done right: roles, ownership checks and identity - November 13, 2026
- GDPR-compliant logging in Spring Boot, part 3: the personal-data leaks outside your own code - October 19, 2026
- GDPR-compliant logging in Spring Boot, part 2: a build-time test that fails on personal data in log statements - October 19, 2026

