Quarkus - Quarkus Extension for Spring Web API

While users are encouraged to use JAX-RS annotation for defining REST endpoints, Quarkus provides a compatibility layer for Spring Web in the form of the spring-web extension.

This guide explains how a Quarkus application can leverage the well known Spring Web annotations to define RESTful services.

This technology is considered preview.

In preview, backward compatibility and presence in the ecosystem is not guaranteed. Specific improvements might require to change configuration or APIs and plans to become stable are under way. Feedback is welcome on our mailing list or as issues in our GitHub issue tracker.

For a full list of possible extension statuses, check our FAQ entry.

Prerequisites

To complete this guide, you need:

  • less than 15 minutes

  • an IDE

  • JDK 1.8+ installed with JAVA_HOME configured appropriately

  • Apache Maven 3.6.2+

Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

Clone the Git repository: git clone [https://github.com/quarkusio/quarkus-quickstarts.git](https://github.com/quarkusio/quarkus-quickstarts.git), or download an archive.

The solution is located in the spring-web-quickstart directory.

Creating the Maven project

First, we need a new project. Create a new project with the following command:

  1. mvn io.quarkus:quarkus-maven-plugin:1.7.6.Final:create \
  2. -DprojectGroupId=org.acme \
  3. -DprojectArtifactId=spring-web-quickstart \
  4. -DclassName="org.acme.spring.web.GreetingController" \
  5. -Dpath="/greeting" \
  6. -Dextensions="spring-web"
  7. cd spring-web-quickstart

This command generates a Maven project with a REST endpoint and imports the spring-web extension.

If you already have your Quarkus project configured, you can add the spring-web extension to your project by running the following command in your project base directory:

  1. ./mvnw quarkus:add-extension -Dextensions="spring-web"

This will add the following to your pom.xml:

  1. <dependency>
  2. <groupId>io.quarkus</groupId>
  3. <artifactId>quarkus-spring-web</artifactId>
  4. </dependency>

GreetingController

The Quarkus maven plugin automatically generated a controller with the Spring Web annotations to define our REST endpoint (instead of the JAX-RS ones used by default) The src/main/java/org/acme/spring/web/GreetingController.java file looks as follows:

  1. package org.acme.spring.web;
  2. import org.springframework.web.bind.annotation.GetMapping;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. @RestController
  6. @RequestMapping("/greeting")
  7. public class GreetingController {
  8. @GetMapping
  9. public String hello() {
  10. return "hello";
  11. }
  12. }

GreetingControllerTest

Note that a test for the controller has been created as well:

  1. package org.acme.spring.web;
  2. import io.quarkus.test.junit.QuarkusTest;
  3. import org.junit.jupiter.api.Test;
  4. import static io.restassured.RestAssured.given;
  5. import static org.hamcrest.CoreMatchers.is;
  6. @QuarkusTest
  7. public class GreetingControllerTest {
  8. @Test
  9. public void testHelloEndpoint() {
  10. given()
  11. .when().get("/greeting")
  12. .then()
  13. .statusCode(200)
  14. .body(is("hello"));
  15. }
  16. }

Package and run the application

Run the application with: ./mvnw compile quarkus:dev. Open your browser to http://localhost:8080/greeting.

The result should be: {"message": "hello"}.

Run the application as a native executable

You can of course create a native image using the instructions of the Building a native executable guide.

Going further with an endpoint returning JSON

The GreetingController above was an example of a very simple endpoint. In many cases however it is required to return JSON content. The following example illustrates how that could be achieved using a Spring RestController:

  1. import org.springframework.web.bind.annotation.GetMapping;
  2. import org.springframework.web.bind.annotation.PathVariable;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. @RestController
  6. @RequestMapping("/greeting")
  7. public class GreetingController {
  8. @GetMapping("/{name}")
  9. public Greeting hello(@PathVariable(name = "name") String name) {
  10. return new Greeting("hello " + name);
  11. }
  12. public static class Greeting {
  13. private final String message;
  14. public Greeting(String message) {
  15. this.message = message;
  16. }
  17. public String getMessage(){
  18. return message;
  19. }
  20. }
  21. }

The corresponding test could look like:

  1. package org.acme.spring.web;
  2. import io.quarkus.test.junit.QuarkusTest;
  3. import org.junit.jupiter.api.Test;
  4. import static io.restassured.RestAssured.given;
  5. import static org.hamcrest.CoreMatchers.is;
  6. @QuarkusTest
  7. public class GreetingControllerTest {
  8. @Test
  9. public void testHelloEndpoint() {
  10. given()
  11. .when().get("/greeting/quarkus")
  12. .then()
  13. .statusCode(200)
  14. .body("message", is("hello quarkus"));
  15. }
  16. }

It should be noted that when using the Spring Web support in Quarkus, Jackson is automatically added to the classpath and properly setup.

Adding OpenAPI and Swagger-UI

You can add support for OpenAPI and Swagger-UI by using the quarkus-smallrye-openapi extension.

Add the extension by running this command:

  1. ./mvnw quarkus:add-extension -Dextensions="io.quarkus:quarkus-smallrye-openapi"

This will add the following to your pom.xml:

  1. <dependency>
  2. <groupId>io.quarkus</groupId>
  3. <artifactId>quarkus-smallrye-openapi</artifactId>
  4. </dependency>

This is enough to generate a basic OpenAPI schema document from your REST Endpoints:

  1. curl http://localhost:8080/openapi

You will see the generated OpenAPI schema document:

  1. ---
  2. openapi: 3.0.1
  3. info:
  4. title: Generated API
  5. version: "1.0"
  6. paths:
  7. /greeting:
  8. get:
  9. responses:
  10. "200":
  11. description: OK
  12. content:
  13. '*/*':
  14. schema:
  15. type: string
  16. /greeting/{name}:
  17. get:
  18. parameters:
  19. - name: name
  20. in: path
  21. required: true
  22. schema:
  23. type: string
  24. responses:
  25. "200":
  26. description: OK
  27. content:
  28. '*/*':
  29. schema:
  30. $ref: '#/components/schemas/Greeting'
  31. components:
  32. schemas:
  33. Greeting:
  34. type: object
  35. properties:
  36. message:
  37. type: string

Also see the OpenAPI Guide

Adding MicroProfile OpenAPI Annotations

You can use MicroProfile OpenAPI to better document your schema, example, adding the following to the class level of the GreetingController:

  1. @OpenAPIDefinition(
  2. info = @Info(
  3. title="Greeting API",
  4. version = "1.0.1",
  5. contact = @Contact(
  6. name = "Greeting API Support",
  7. url = "http://exampleurl.com/contact",
  8. email = "techsupport@example.com"),
  9. license = @License(
  10. name = "Apache 2.0",
  11. url = "http://www.apache.org/licenses/LICENSE-2.0.html"))
  12. )

And describe your endpoints like this:

  1. @Tag(name = "Hello", description = "Just say hello")
  2. @GetMapping(produces=MediaType.TEXT_PLAIN_VALUE)
  3. public String hello() {
  4. return "hello";
  5. }
  6. @GetMapping(value = "/{name}", produces=MediaType.APPLICATION_JSON_VALUE)
  7. @Tag(name = "Hello to someone", description = "Just say hello to someone")
  8. public Greeting hello(@PathVariable(name = "name") String name) {
  9. return new Greeting("hello " + name);
  10. }

will generate this OpenAPI schema:

  1. ---
  2. openapi: 3.0.1
  3. info:
  4. title: Greeting API
  5. contact:
  6. name: Greeting API Support
  7. url: http://exampleurl.com/contact
  8. email: techsupport@example.com
  9. license:
  10. name: Apache 2.0
  11. url: http://www.apache.org/licenses/LICENSE-2.0.html
  12. version: 1.0.1
  13. tags:
  14. - name: Hello
  15. description: Just say hello
  16. - name: Hello to someone
  17. description: Just say hello to someone
  18. paths:
  19. /greeting:
  20. get:
  21. tags:
  22. - Hello
  23. responses:
  24. "200":
  25. description: OK
  26. content:
  27. '*/*':
  28. schema:
  29. type: string
  30. /greeting/{name}:
  31. get:
  32. tags:
  33. - Hello to someone
  34. parameters:
  35. - name: name
  36. in: path
  37. required: true
  38. schema:
  39. type: string
  40. responses:
  41. "200":
  42. description: OK
  43. content:
  44. '*/*':
  45. schema:
  46. $ref: '#/components/schemas/Greeting'
  47. components:
  48. schemas:
  49. Greeting:
  50. type: object
  51. properties:
  52. message:
  53. type: string

Using Swagger UI

Swagger UI is included by default when running in Dev or Test mode, and can optionally added to Prod mode. See the Swagger UI Guide for more details.

Navigate to localhost:8080/swagger-ui/ and you will see the Swagger UI screen:

Swagger UI

Supported Spring Web functionalities

Quarkus currently supports a subset of the functionalities that Spring Web provides. More specifically Quarkus supports the REST related features of Spring Web (think of @RestController instead of @Controller).

Annotations

The table below summarizes the supported annotations:

Table 1. Supported Spring Web annotation
NameComments

@RestController

@RequestMapping

@GetMapping

@PostMapping

@PutMapping

@DeleteMapping

@PatchMapping

@RequestParam

@RequestHeader

@MatrixVariable

@PathVariable

@CookieValue

@RequestBody

@ResponseStatus

@ExceptionHandler

Can only be used in a @RestControllerAdvice class, not on a per-controller basis

@RestControllerAdvice

Only the @ExceptionHandler capability is supported

Controller method return types

The following method return types are supported:

  • Primitive types

  • String (which will be used as a literal, no Spring MVC view support is provided)

  • POJO classes which will be serialized via JSON

  • org.springframework.http.ResponseEntity

Controller method parameter types

In addition to the method parameters that can be annotated with the appropriate Spring Web annotations from the previous table, javax.servlet.http.HttpServletRequest and javax.servlet.http.HttpServletResponse are also supported. For this to function however, users need to add the quarkus-undertow dependency.

Exception handler method return types

The following method return types are supported:

  • org.springframework.http.ResponseEntity

  • java.util.Map

Other return types mentioned in the Spring [ExceptionHandler javadoc](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/ExceptionHandler.html) are not supported.

Exception handler method parameter types

The following parameter types are supported, in arbitrary order:

  • An exception argument: declared as a general Exception or as a more specific exception. This also serves as a mapping hint if the annotation itself does not narrow the exception types through its value().

  • Request and/or response objects (typically from the Servlet API). You may choose any specific request/response type, e.g. ServletRequest / HttpServletRequest. To use Servlet API, the quarkus-undertow dependency needs to be added.

Other parameter types mentioned in the Spring [ExceptionHandler javadoc](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/ExceptionHandler.html) are not supported.

Important Technical Note

Please note that the Spring support in Quarkus does not start a Spring Application Context nor are any Spring infrastructure classes run. Spring classes and annotations are only used for reading metadata and / or are used as user code method return types or parameter types. What that means for end users, is that adding arbitrary Spring libraries will not have any effect. Moreover Spring infrastructure classes (like org.springframework.beans.factory.config.BeanPostProcessor for example) will not be executed.

Conversion Table

The following table shows how Spring Web annotations can be converted to JAX-RS annotations.

SpringJAX-RSComments

@RequestController

There is no equivalent in JAX-RS. Annotating a class with @Path suffices

@RequestMapping(path=”/api”)

@Path(“/api”)

@RequestMapping(consumes=”application/json”)

@Consumes(“application/json”)

@RequestMapping(produces=”application/json”)

@Produces(“application/json”)

@RequestParam

@QueryParam

@PathVariable

@PathParam

@RequestBody

No equivalent in JAX-RS. Method parameters corresponding to the body of the request are handled in JAX-RS without requiring any annotation

@RestControllerAdvice

No equivalent in JAX-RS

@ResponseStatus

No equivalent in JAX-RS

@ExceptionHandler

No equivalent annotation in JAX-RS. Exceptions are handled by implementing javax.ws.rs.ext.ExceptionMapper

More Spring guides

Quarkus has more Spring compatibility features. See the following guides for more details: