Getting started with Quarkus

Guide
  • Red Hat build of Quarkus 2.13
  • Updated 26 January 2024
  • Published 15 December 2022

Getting started with Quarkus

Guide
Red Hat build of Quarkus 2.13
  • Updated 26 January 2024
  • Published 15 December 2022

As an application developer, you can use Red Hat build of Quarkus to create microservices-based applications written in Java that run on OpenShift environments. Quarkus applications can run on top of a Java virtual machine (JVM) or be compiled to native executables. Native applications have a smaller memory footprint and a faster startup time than their JVM counterpart.

You can create a Quarkus application in either of the following ways:

  • Using Apache Maven and the Quarkus Maven plugin

  • Using code.quarkus.redhat.com

  • Using the Quarkus command-line interface (CLI)

You can get started with Quarkus and create, test, package, and run a simple Quarkus project that exposes a hello HTTP endpoint. To demonstrate dependency injection, the hello HTTP endpoint uses a greeting bean.

78 OpenShift Quarkus Arch 0420

For a completed example of the getting started exercise, download the Quarkus quickstart archive or clone the Quarkus Quickstarts Git repository and go to the getting-started directory.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. We are beginning with these four terms: master, slave, blacklist, and whitelist. Because of the enormity of this endeavor, these changes will be implemented gradually over several upcoming releases. For more details, see our CTO Chris Wright’s message.

1. About Red Hat build of Quarkus

Red Hat build of Quarkus is a Kubernetes-native Java stack that is optimized for use with containers and Red Hat OpenShift Container Platform. Quarkus is designed to work with popular Java standards, frameworks, and libraries such as Eclipse MicroProfile, Eclipse Vert.x, Apache Camel, Apache Kafka, Hibernate ORM with Java Persistence API (JPA), and RESTEasy (JAX-RS).

As a developer, you can choose the Java frameworks you want for your Java applications, which you can run in Java Virtual Machine (JVM) mode or compile and run in native mode. Quarkus provides a container-first approach to building Java applications. The container-first approach facilitates the containerization and efficient execution of microservices and functions. For this reason, Quarkus applications have a smaller memory footprint and faster startup times.

Quarkus also optimizes the application development process with capabilities such as unified configuration, automatic provisioning of unconfigured services, live coding, and continuous testing that gives you instant feedback on your code changes.

For information about the differences between the Quarkus community version and Red Hat build of Quarkus, see Differences between the Quarkus community version and Red Hat build of Quarkus.

2. Preparing your environment

Before you start using Quarkus, you must prepare your environment.

Procedure
  • Confirm the following installations are completed on your system:

    • You have installed OpenJDK 11 or 17 and set the JAVA_HOME environment variable to specify the location of the Java SDK.

      • To download Red Hat build of OpenJDK, log in to the Red Hat Customer Portal and go to Software Downloads.

    • You have installed Apache Maven 3.8.x, where x is 6 or later. Apache Maven is available from the Apache Maven Project website.

    • Optional: If you want to use the Quarkus command-line interface (CLI), ensure that it is installed.

      • For instructions on how to install the Quarkus CLI, refer to the community-specific information at Quarkus CLI.

The Quarkus CLI is intended for development mode only. Red Hat does not support using the Quarkus CLI in production environments.

2.1. About Quarkus BOMs

From Red Hat build of Quarkus 2.2, dependency versions of all core Quarkus extensions are managed by using the com.redhat.quarkus.platform:quarkus-bom file.

The purpose of the Bill of Materials (BOM) file is to manage dependency versions of Quarkus artifacts in your project so that when you use a BOM in your project, you do not need to specify which dependency versions work together. Instead, you can import the Quarkus BOM file to the pom.xml configuration file, where the dependency versions are included in the <dependencyManagement> section. Therefore, you do not need to list the versions of individual Quarkus dependencies that are managed by the specified BOM in the pom.xml file.

To view information about supported extension-specific BOMs that are available with Red Hat build of Quarkus, see Red Hat build of Quarkus Component Details.

You only need to import the member-specific BOM for the platform-member extensions that you use in your application. Therefore, you have fewer dependencies to manage as compared to a monolithic single BOM. Because every member-specific BOM is a fragment of the universal Quarkus BOM, you can import the member BOMs in any order without creating a conflict.

2.2. About Apache Maven and Quarkus

Apache Maven is a distributed build automation tool that is used in Java application development to create, manage, and build software projects. Maven uses standard configuration files called Project Object Model (POM) files to define projects and manage the build process. POM files describe the module and component dependencies, build order, and targets for the resulting project packaging and output by using an XML file, ensuring that the project gets built correctly and uniformly.

Maven repositories

A Maven repository stores Java libraries, plugins, and other build artifacts. The default public repository is the Maven 2 Central Repository, but repositories can be private and internal within a company to share common artifacts among development teams. Repositories are also available from third parties.

You can use the Red Hat-hosted Maven repository with your Quarkus projects or you can download the Red Hat build of Quarkus Maven repository.

Maven plugins

Maven plugins are defined parts of a POM file that run one or more tasks. Red Hat build of Quarkus applications use the following Maven plugins:

  • Quarkus Maven plugin (quarkus-maven-plugin): Enables Maven to create Quarkus projects, packages your applications into JAR files, and provides a development mode.

  • Maven Surefire plugin (maven-surefire-plugin): When Quarkus enables the test profile, the Maven Surefire plugin is used during the test phase of the build life cycle to execute unit tests on your application. The plugin generates text and XML files that contain the test reports.

2.3. Configuring the Maven settings.xml file for the online repository

To use the Red Hat-hosted Quarkus repository with your Quarkus Maven project, configure the settings.xml file for your user. Maven settings that are used with a repository manager or a repository on a shared server offer better control and manageability of projects.

When you configure the repository by modifying the Maven settings.xml file, the changes apply to all of your Maven projects. If you want to apply the configuration to a specific project only, use the -s option and specify the path to the project-specific settings.xml file.

Procedure
  1. Open the Maven $HOME/.m2/settings.xml file in a text editor or an integrated development environment (IDE).

    If no settings.xml file is present in the $HOME/.m2/ directory, copy the settings.xml file from the $MAVEN_HOME/.m2/conf/ directory into the $HOME/.m2/ directory.

  2. Add the following lines to the <profiles> element of the settings.xml file:

    <!-- Configure the Quarkus Maven repository -->
    <profile>
      <id>red-hat-enterprise-maven-repository</id>
      <repositories>
        <repository>
          <id>red-hat-enterprise-maven-repository</id>
          <url>https://maven.repository.redhat.com/ga/</url>
          <releases>
            <enabled>true</enabled>
          </releases>
          <snapshots>
            <enabled>false</enabled>
          </snapshots>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <id>red-hat-enterprise-maven-repository</id>
          <url>https://maven.repository.redhat.com/ga/</url>
          <releases>
            <enabled>true</enabled>
          </releases>
          <snapshots>
            <enabled>false</enabled>
          </snapshots>
        </pluginRepository>
      </pluginRepositories>
    </profile>
  3. Add the following lines to the <activeProfiles> element of the settings.xml file and save the file.

    <activeProfile>red-hat-enterprise-maven-repository</activeProfile>

2.4. Configuring the Quarkus Maven repository

If you do not want to use the online Maven repository, you can download and configure the Quarkus Maven repository to create a Quarkus application with Maven. The Quarkus Maven repository contains several dependencies that Java developers typically use to build their applications. This procedure shows how to edit the settings.xml file to configure the Quarkus Maven repository.

When you configure the repository by modifying the Maven settings.xml file, the changes apply to all your Maven projects. If you want to apply the configuration to a specific project, use the -s option and specify the path to the project-specific settings.xml file.

Procedure
  1. Log in to the Red Hat Customer Portal, go to Software Downloads, and download the Quarkus Maven repository ZIP file.

  2. Extract the downloaded archive.

  3. Go to the $HOME/.m2/ directory and open the Maven settings.xml file in a text editor or an integrated development environment (IDE).

  4. Add the path of the Quarkus Maven repository that you downloaded to the <profiles> element of the settings.xml file. The format of the path of the Quarkus Maven repository must be file://$PATH, for example, file:///home/userX/<root-directory-of-the-downloaded-archive>/maven-repository.

    <!-- Configure the Quarkus Maven repository -->
    <profile>
      <id>red-hat-enterprise-maven-repository</id>
      <repositories>
        <repository>
          <id>red-hat-enterprise-maven-repository</id>
          <url>file:///path/to/Quarkus/Maven/repository/</url>
          <releases>
            <enabled>true</enabled>
          </releases>
          <snapshots>
            <enabled>false</enabled>
          </snapshots>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <id>red-hat-enterprise-maven-repository</id>
          <url>file:///path/to/Quarkus/Maven/repository/</url>
          <releases>
            <enabled>true</enabled>
          </releases>
          <snapshots>
            <enabled>false</enabled>
          </snapshots>
        </pluginRepository>
      </pluginRepositories>
    </profile>
  5. Add the following lines to the <activeProfiles> element of the settings.xml file and save the file.

    <activeProfile>red-hat-enterprise-maven-repository</activeProfile>

If your Maven repository contains outdated artifacts, you might encounter one of the following Maven error messages when you build or deploy your project:

  • Missing artifact <project_name>

  • [ERROR] Failed to execute goal on project <artifact_name>; Could not resolve dependencies for <project_name>

Where:

  • <artifact_name> is the name of a missing artifact

  • <project_name> is the name of the project you are trying to build

To resolve these issues, force a download of the latest Maven artifacts by deleting the cached version of your local repository, which is located in the $HOME/.m2/repository directory.

2.5. Reconfiguring your Maven project to Red Hat build of Quarkus

You can migrate a Quarkus community project to Red Hat build of Quarkus by changing the Maven configuration in your project POM file.

Prerequisites
Procedure
  • Change the following values in the <properties> section of the pom.xml file of your project:

    • Change the value of the <quarkus.platform.group-id> property to com.redhat.quarkus.platform.

    • Change the value of the <quarkus.platform.version> property to 2.13.9.Final-redhat-00004.

      pom.xml
      <project>
        ...
        <properties>
           ...
           <quarkus.platform.group-id>com.redhat.quarkus.platform</quarkus.platform.group-id>
           <quarkus.platform.artifact-id>quarkus-bom</quarkus.platform.artifact-id>
           <quarkus.platform.version>2.13.9.Final-redhat-00004</quarkus.platform.version>
           ...
        </properties>
        ...
      </project>

3. Configuring Quarkus developer tools

By using Quarkus developer tools, you can complete tasks such as:

  • Creating a Maven project for your application

  • Adding and configuring an extension to use in your application

  • Deploying your application on an OpenShift cluster

3.1. Configuring Quarkus extension registry client

The extension registry, registry.quarkus.redhat.com, hosts the Quarkus extensions that Red Hat provides. You can configure your Quarkus developer tools to access extensions in this registry by adding the registry to your registry client configuration file. The registry client configuration file is a YAML file that contains a list of registries.

  • The default Quarkus registry is registry.quarkus.io; typically, you do not need to configure it. However, if a user provides a custom registry list and registry.quarkus.io is not on it, then registry.quarkus.io is not enabled.

  • Ensure that the registry you prefer appears first on the registry list. When Quarkus developer tools search for registries, they begin at the top of the list.

Procedure
  1. Open the config.yaml file that contains your extension registry configuration. When you configure your extension registries for the first time, you might need to create a config.yaml file in the <user_home_directory_name>/.quarkus directory on your machine.

  2. Add the new registry to the config.yaml file. For example:

    config.yaml
    registries:
      - registry.quarkus.redhat.com
      - registry.quarkus.io

4. Creating the Getting Started project

By creating a getting-started project, you can get up and running with a simple Quarkus application. You can create a getting-started project in one of the following ways:

  • Using Apache Maven and the Quarkus Maven plugin

  • Using code.quarkus.redhat.com to generate a Quarkus Maven project

  • Using the Quarkus command-line interface (CLI)

Prerequisites
Procedure
  • Depending on your requirements, select the method you want to use to create your getting-started project.

4.1. Creating the Getting Started project by using Apache Maven

You can create a getting-started project by using Apache Maven and the Quarkus Maven plugin. With this getting-started project, you can get up and running with a simple Quarkus application.

Prerequisites
Procedure
  1. To verify that Maven is using OpenJDK 11 or 17, that the Maven version is 3.8.x, where x is 6 or later, and that mvn is accessible from the PATH environment variable, enter the following command:

    mvn --version
  2. If the preceding command does not return OpenJDK 11 or 17, add the path to OpenJDK 11 or 17 to the PATH environment variable and enter the preceding command again.

  3. To generate the project, enter one of the following commands:

    Apple macOS and Microsoft Windows are supported as developer environments, but are not supported as production environments.

    • If you are using Linux or Apple macOS, enter the following command:

      mvn com.redhat.quarkus.platform:quarkus-maven-plugin:2.13.9.Final-redhat-00004:create \
          -DprojectGroupId=org.acme \
          -DprojectArtifactId=getting-started \
          -DplatformGroupId=com.redhat.quarkus.platform \
          -DplatformVersion=2.13.9.Final-redhat-00004 \
          -DclassName="org.acme.quickstart.GreetingResource" \
          -Dpath="/hello"
      cd getting-started
    • If you are using the Microsoft Windows command line, enter the following command:

      mvn com.redhat.quarkus.platform:quarkus-maven-plugin:2.13.9.Final-redhat-00004:create
      -DprojectGroupId=org.acme -DprojectArtifactId=getting-started
      -DplatformGroupId=com.redhat.quarkus.platform
      -DplatformVersion=2.13.9.Final-redhat-00004
      -DclassName="org.acme.quickstart.GreetingResource"
      -Dpath="/hello"
    • If you are using the Microsoft Windows Powershell, enter the following command:

      mvn com.redhat.quarkus.platform:quarkus-maven-plugin:2.13.9.Final-redhat-00004:create
      "-DprojectGroupId=org.acme"
      "-DprojectArtifactId=getting-started"
      "-DplatformVersion=2.13.9.Final-redhat-00004"
      "-DplatformGroupId=com.redhat.quarkus.platform"
      "-DclassName=org.acme.quickstart.GreetingResource"
      "-Dpath=/hello"

      These commands create the following elements in the ./getting-started directory:

      • The Maven project directory structure

      • An org.acme.quickstart.GreetingResource resource exposed on /hello

      • Associated unit tests for testing your application in native mode and JVM mode

      • A landing page that is accessible on http://localhost:8080 after you start the application

      • Example Dockerfiles in the src/main/docker directory

      • The application configuration file

  4. After the directory structure is created, open the pom.xml file in a text editor and examine the contents of the file:

    pom.xml
    <project>
      ...
      <properties>
         ...
         <quarkus.platform.group-id>com.redhat.quarkus.platform</quarkus.platform.group-id>
         <quarkus.platform.artifact-id>quarkus-bom</quarkus.platform.artifact-id>
         <quarkus.platform.version>2.13.9.Final-redhat-00004</quarkus.platform.version>
         ...
      </properties>
      ...
      <dependencyManagement>
          <dependencies>
            <dependency>
              <groupId>${quarkus.platform.group-id}</groupId>
              <artifactId>${quarkus.platform.artifact-id}</artifactId>
              <version>${quarkus.platform.version}</version>
              <type>pom</type>
              <scope>import</scope>
            </dependency>
          </dependencies>
      </dependencyManagement>
      ...
      <build>
          ...
          <plugins>
            ...
            <plugin>
              <groupId>${quarkus.platform.group-id}</groupId>
              <artifactId>quarkus-maven-plugin</artifactId>
              <version>${quarkus.platform.version}</version>
              <extensions>true</extensions>
              <executions>
                <execution>
                  <goals>
                    <goal>build</goal>
                    <goal>generate-code</goal>
                    <goal>generate-code-tests</goal>
                  </goals>
                </execution>
              </executions>
            </plugin>
            ...
          </plugins>
          ...
      </build>
     ...
    </project>

    The <dependencyManagement> section of the pom.xml file contains the Quarkus BOM. Therefore, you do not need to list the versions of individual Quarkus dependencies in the pom.xml file. In the pom.xml file, you can also find the quarkus-maven-plugin plugin that is responsible for packaging the application.

  5. Review the quarkus-resteasy-reactive dependency in the pom.xml file. This dependency enables you to develop REST applications:

    <dependency>
        <groupId>io.quarkus</groupId>
        <artifactId>quarkus-resteasy-reactive</artifactId>
    </dependency>
  6. Review the src/main/java/org/acme/quickstart/GreetingResource.java file:

    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    {CompanyName}
    @Path("/hello")
    public class GreetingResource {
    
        @GET
        @Produces(MediaType.TEXT_PLAIN)
        public String hello() {
            return "Hello from RESTEasy Reactive";
        }
    }

    This file contains a simple REST endpoint that returns hello as a response to a request that you send to the /hello endpoint.

    With Quarkus, the Application class for JAX-RS is supported but not required. In addition, only one instance of the GreetingResource class is created and not one per request. You can configure this by using different *Scoped annotations, for example ApplicationScoped, RequestScoped, and so on.

4.2. Creating the Getting Started project by using code.quarkus.redhat.com

As an application developer, you can use code.quarkus.redhat.com to generate a Quarkus Maven project and automatically add and configure the extensions that you want to use in your application. In addition, code.quarkus.redhat.com automatically manages the configuration parameters that are required to compile your project into a native executable.

You can generate a Quarkus Maven project, including the following activities:

  • Specifying basic details about your application

  • Choosing the extensions that you want to include in your project

  • Generating a downloadable archive with your project files

  • Using custom commands for compiling and starting your application

Prerequisites
  • You have a web browser.

  • You have prepared your environment to use Apache Maven, as outlined in

Preparing your environment.

  • You have configured your Quarkus Maven repository. You can use either the Red Hat-hosted Quarkus repository or you can download and configure the Quarkus Maven repository to create a Quarkus application with Maven.

  • Optional: You have installed the Quarkus command-line interface (CLI), which is one of the methods you can use to start Quarkus in development mode.

For more information, see Installing the Quarkus CLI.

The Quarkus CLI is intended for development mode only. Red Hat does not support using the Quarkus CLI in production environments.

Procedure
  1. On your web browser, navigate to https://code.quarkus.redhat.com.

  2. Specify basic details about your project:

    Screenshot of the basic application details section on the code.quarkus.redhat.com site
    1. Enter a group name for your project. The name format follows the Java package naming convention, for example, org.acme.

    2. Enter a name that you want to use for Maven artifacts that are generated from your project, for example, code-with-quarkus.

    3. Select the build tool that you want to use to compile and start your application. The build tool that you choose determines the following setups:

      • The directory structure of your generated project

      • The format of configuration files that are used in your generated project

      • The custom build script and command for compiling and starting your application that code.quarkus.redhat.com displays for you after you generate your project

        Red Hat provides support for using code.quarkus.redhat.com to create Quarkus Maven projects only.

  3. Specify additional details about your application project:

    1. To display the fields that contain further application details, select More options.

    2. Enter a version that you want to use for artifacts that are generated from your project. The default value of this field is 1.0.0-SNAPSHOT. Using semantic versioning is recommended; however, you can choose to specify a different type of versioning.

    3. Select whether you want code.quarkus.redhat.com to add starter code to your project. When you add extensions that are marked with "CODE" to your project, you can enable this option to automatically create example class and resource files for those extensions when you generate your project. However, this option does not affect your generated project if you do not add any extensions that provide an example code.

      Screenshot of the application details section on the code.quarkus.redhat.com site showing the extended form with additional application details

    The code.quarkus.redhat.com repository automatically uses the latest release of Red Hat build of Quarkus. You can manually change the BOM version in the pom.xml file after you generate your project.

  4. Select the extensions that you want to use. The extensions that you select are included as dependencies of your Quarkus application. The Quarkus platform also ensures that these extensions are compatible with future versions.

    Do not use the RESTEasy and the RESTEasy Reactive extensions in the same project.

    The quark icon (quark) next to an extension indicates that the extension is part of the Red Hat build of Quarkus platform release. Red Hat recommends that you use extensions from the same platform, because they are tested and verified together, and are therefore easier to use and upgrade.

    You can enable the option to automatically generate starter code for extensions that are marked with STARTER-CODE.

    Screenshot of the list of extensions at the code.quarkus.redhat.com site that you can add to your project

  5. To confirm your choices, select Generate your application. The following items are displayed:

    • A link to download the archive that contains your generated project

    • A custom command that you can use to compile and start your application

  6. To save the archive with the generated project files to your machine, select Download the ZIP.

  7. Extract the contents of the archive.

  8. Go to the directory that contains your extracted project files:

    cd <directory_name>
  9. To compile and start your application in development mode, use one of the following ways:

    • Using Maven:

      ./mvnw quarkus:dev
    • Using the Quarkus CLI:

      quarkus dev

4.2.1. Support levels for Quarkus extensions

Red Hat provides different levels of support for extensions that are available on code.quarkus.redhat.com that you can add to your Quarkus project. Labels next to the name of each extension indicate the support level.

Screenshot of an expanded overflow menu next to one of the extensions on code.quarkus.redhat.coim showing the custom commands that you can copy

Red Hat does not support unlabeled extensions for use in production environments.

Quarkus provides the following levels of support for Quarkus extensions: .Support levels provided by Quarkus for Quarkus extensions.

Support level Description

SUPPORTED

Red Hat fully supports extensions for use in enterprise applications in production environments.

TECH-PREVIEW

Red Hat offers limited support to extensions in production environments under the Technology Preview Features Support Scope.

DEV-SUPPORT

Red Hat does not support extensions for use in production environments, but Red Hat developers support the core functionality that they provide for use in developing new applications.

DEPRECATED

Red Hat plans to replace extensions with more recent technology or implementation that provides the same functionality.

STARTER-CODE

You can automatically generate the example code for extensions.

By clicking the arrow icon (⌄) beside each of the extensions, you can expand the overflow menu to access further actions for that extension. For example:

  • Add the extension to an existing project by using the Quarkus Maven plugin on the command line

  • Copy an XML snippet to add the extension to a project’s pom.xml file

  • Obtain the groupId, artifactId, and version of each extension

  • Open the extension guide

4.3. Creating the Getting Started project by using the Quarkus CLI

You can create your getting-started project by using the Quarkus command-line interface (CLI).

With the Quarkus CLI, you can create projects, manage extensions, and run build and development commands.

The Quarkus CLI is intended for development mode only. Red Hat does not support using the Quarkus CLI in production environments.

Prerequisites
Procedure
  1. To generate the project, in a command terminal, enter the following command:

    quarkus create && cd code-with-quarkus

    You can also specify the 'app' subcommand, for example, quarkus create app. However, it is not mandatory to do so because the 'app' subcommand is implied if it is not specified.

    With this command, the Quarkus project is created in a folder called 'code-with-quarkus' in your current working directory.

  2. By default, the groupId, artifactId, and version attributes are specified with the following default values:

    • groupId='org.acme'

    • artifactId='code-with-quarkus'

    • version='1.0.0-SNAPSHOT'

      To change the values of the groupId, artifactId, and version attributes, issue the quarkus create command and specify the following syntax on the CLI:

      groupId:artifactId:version

      For example, quarkus create app mygroupId:myartifactid:version

    To view information about all the available Quarkus commands, specify the help parameter:

    quarkus --help
  3. Review the src/main/java/org/acme/GreetingResource.java file in a text editor:

    package org.acme;
    
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    
    @Path("/hello")
    public class GreetingResource {
    
        @GET
        @Produces(MediaType.TEXT_PLAIN)
        public String hello() {
            return "Hello from RESTEasy Reactive";
        }
    }

    This file contains a simple REST endpoint that returns hello as a response to a request that you send to the /hello endpoint.

Verification
  1. Compile and start your application in development mode.

  2. Package and run your Getting Started project from the Quarkus CLI.

5. Compiling and starting the Quarkus Getting Started project

After you create the Quarkus Getting Started project, you can compile the Hello application and verify that the hello endpoint returns hello.

This procedure uses the Quarkus built-in development mode, so you can update the application sources and configurations while your application is running. The changes you make appear in the running application.

The command that you use to compile your Quarkus Hello application depends on the developer tool that you installed on the machine.

Prerequisites
  • You have created the Quarkus Getting Started project.

Procedure
  1. Go to the project directory.

  2. To compile the Quarkus Hello application in development mode, use one of the following methods, depending on the developer tool that you intend to use:

    • If you prefer to use Apache Maven, enter the following command:

      mvn quarkus:dev
    • If you prefer to use the Quarkus command-line interface (CLI), enter the following command:

      quarkus dev
    • If you prefer to use the Maven wrapper, enter the following command:

      ./mvnw quarkus:dev
      Expected output

      The following extract shows an example of the expected output:

      INFO  [io.quarkus] (Quarkus Main Thread) Profile dev activated. Live Coding activated.
      INFO  [io.quarkus] (Quarkus Main Thread) Installed features: [cdi, resteasy, smallrye-context-propagation]
Verification
  • To send a request to the endpoint that is provided by the application, enter the following command in a new terminal window:

    curl -w "\n" http://localhost:8080/hello
    Hello from RESTEasy Reactive

    The "\n" attribute automatically adds a new line before the output of the command, which prevents your terminal from printing a '%' character or putting both the result and the next shell prompt on the same line.

6. Using Quarkus dependency injection

Dependency injection enables a service to be used in a way that is completely independent of any client consumption. It separates the creation of client dependencies from the client’s behavior, which enables program designs to be loosely coupled.

Dependency injection in Red Hat build of Quarkus is based on Quarkus ArC, which is a Contexts and Dependency Injection (CDI)-based build-time oriented dependency injection solution that is tailored for Quarkus architecture. Because ArC is a transitive dependency of quarkus-resteasy, and quarkus-resteasy is a dependency of your project, ArC is downloaded already.

Prerequisites
  • You have created the Quarkus Getting Started project.

Procedure
  1. To modify the application and add a companion bean, create the src/main/java/org/acme/quickstart/GreetingService.java file with the following content:

    package org.acme.quickstart;
    
    import javax.enterprise.context.ApplicationScoped;
    
    @ApplicationScoped
    public class GreetingService {
    
        public String greeting(String name) {
            return "hello " + name;
        }
    
    }
  2. Edit the src/main/java/org/acme/quickstart/GreetingResource.java to inject the GreetingService and use it to create a new endpoint:

    package org.acme.quickstart;
    
    import javax.inject.Inject;
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    
    import org.jboss.resteasy.annotations.jaxrs.PathParam;
    
    @Path("/hello")
    public class GreetingResource {
    
        @Inject
        GreetingService service;
    
        @GET
        @Produces(MediaType.TEXT_PLAIN)
        @Path("/greeting/{name}")
        public String greeting(@PathParam String name) {
            return service.greeting(name);
        }
    
        @GET
        @Produces(MediaType.TEXT_PLAIN)
        public String hello() {
            return "hello";
        }
    }
  3. If you stopped the application, enter the following command to restart it:

    ./mvnw quarkus:dev
  4. To verify that the endpoint returns hello quarkus, enter the following command in a new terminal window:

    curl -w "\n" http://localhost:8080/hello/greeting/quarkus
    hello quarkus

7. Testing your Quarkus application

After you compile your Quarkus Getting Started project, you can verify that it runs as expected by testing your application with the JUnit 5 framework.

Alternatively, you can enable continuous testing of your Quarkus application. For more information, see Enabling and running continuous testing.

The Quarkus project generates the following two test dependencies in the pom.xml file:

  • quarkus-junit5: Required for testing because it provides the @QuarkusTest annotation that controls the JUnit 5 testing framework.

  • rest-assured: The rest-assured dependency is not required but, because it provides a convenient way to test HTTP endpoints, it is integrated. The rest-assured dependency automatically sets the correct URL, so no configuration is required.

Example pom.xml file:

<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-junit5</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <scope>test</scope>
</dependency>

These tests use the REST-assured framework, but you can use a different library if you prefer.

Prerequisites
Procedure
  1. Open the generated pom.xml file and review the contents:

    <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${surefire-plugin.version}</version>
        <configuration>
           <systemPropertyVariables>
             <java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
             <maven.home>${maven.home}</maven.home>
           </systemPropertyVariable>
        </configuration>
    </plugin>

    Note the values of the following properties:

    • The java.util.logging.manager system property is set to ensure that your application uses the correct log manager for the test.

    • The maven.home property points to the location of the settings.xml file, in which you can store the custom Maven configuration that you want to apply to your project.

  2. Edit the src/test/java/org/acme/quickstart/GreetingResourceTest.java file to match the following content:

    package org.acme.quickstart;
    
    import io.quarkus.test.junit.QuarkusTest;
    import org.junit.jupiter.api.Test;
    
    import java.util.UUID;
    
    import static io.restassured.RestAssured.given;
    import static org.hamcrest.CoreMatchers.is;
    
    @QuarkusTest
    public class GreetingResourceTest {
    
        @Test
        public void testHelloEndpoint() {
            given()
              .when().get("/hello")
              .then()
                 .statusCode(200)
                 .body(is("hello"));
        }
    
        @Test
        public void testGreetingEndpoint() {
            String uuid = UUID.randomUUID().toString();
            given()
              .pathParam("name", uuid)
              .when().get("/hello/greeting/{name}")
              .then()
                .statusCode(200)
                .body(is("hello " + uuid));
        }
    
    }

    By using the QuarkusTest runner, you instruct JUnit to start the application before starting the tests.

  3. To run the tests from Maven, enter the following command:

    ./mvnw test

    You can also run the tests from your IDE. If you do this, stop the application first.

    By default, tests run on port 8081 so they do not conflict with the running application. In Quarkus, the RestAssured dependency is configured to use this port.

    If you want to use a different client, use the @TestHTTPResource annotation to directly inject the URL of the tested application into a field in the Test class. This field can be of type String, URL, or URI. You can also enter the test path in the @TestHTTPResource annotation. For example, to test a servlet that is mapped to /myservlet, add the following lines to your test:

    @TestHTTPResource("/myservlet")
    URL testUrl;
  4. If necessary, specify the test port in the quarkus.http.test-port configuration property.

8. Enabling and running continuous testing

With Red Hat build of Quarkus, you can continuously test your code changes as you develop your applications. Quarkus provides a continuous testing feature, which you can run immediately after you make and save a change to the code.

When you run continuous testing, testing is paused after you start the application. You can resume the testing as soon as the application starts. The Quarkus application determines which tests run so that tests are run only on code that has changed.

The continuous testing feature of Quarkus is enabled by default. You can choose to disable continuous testing by setting the quarkus.test.continuous-testing property in the src/main/resources/application.properties file to disabled.

If you disabled continuous testing previously and want to enable it again, you must restart your Quarkus application before you can start testing.

Prerequisites
Procedure
  1. Start your Quarkus application.

    • If you created your Getting Project project by using the code.quarkus.redhat.com or the Quarkus CLI, the Maven wrapper is provided when you generate the project. Enter the following command from your project directory:

      ./mvnw quarkus:dev
    • If you created your Getting Project project by using Apache Maven, which is installed on your machine, enter the following command:

      mvn quarkus:dev
    • If you are running continuous testing in development mode and are using the Quarkus CLI, enter the following command:

      quarkus dev
  2. View details of the testing status in the generated output log.

    To view the output log, you might need to scroll to the bottom of the screen.

    When continuous testing is enabled, the following message is displayed:

    Tests paused, press [r] to resume, [h] for more options>

    By default, when continuous testing is enabled, testing is paused after you start the application. To view the keyboard commands that are available for controlling how you run your tests, see Commands for controlling continuous testing.

  3. To start running the tests, press `r ` on your keyboard.

  4. View the updated output log to monitor the test status and test results, check test statistics, and get guidance for follow-up actions. For example:

    Tests all passed, 2 tests were run, 0 were skipped. Tests took 1470ms.
    Press [r] to re-run, [v] to view full results, [p] to pause, [h] for more options>
Verification
  1. Make a code change. For example, in a text editor, open the src/main/java/GreetingsResource.java file.

  2. Change the "hello" endpoint to return "Hello world" and save the file.

    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    
    @Path("/hello")
    public class GreetingResource {
    
        @GET
        @Produces(MediaType.TEXT_PLAIN)
        public String hello() {
            return "Hello world";
        }
    }
  3. Verify that Quarkus immediately re-runs the test to test the changed code.

  4. View the output log to check the test results. In this example, the test checks whether the changed string contains the value "hello". The test fails because the string was changed to "Hello world".

    2021-05-11 14:21:34,338 ERROR [io.qua.test] (Test runner thread) Test GreetingResourceTest#testHelloEndpoint() failed
    : java.lang.AssertionError: 1 expectation failed.
    Response body doesn't match expectation.
    Expected: is "hello"
      Actual: Hello world
    	at io.restassured.internal.ValidatableResponseImpl.body(ValidatableResponseImpl.groovy)
    	at org.acme.getting.started.GreetingResourceTest.testHelloEndpoint(GreetingResourceTest.java:21)
    --
    Test run failed, 2 tests were run, 1 failed, 0 were skipped. Tests took 295ms
    Press [r] to re-run, [v] to view full results, [p] to pause, [h] for more options>
  5. To exit continuous testing, press Ctrl-C or 'q' on your keyboard.

If you change the value back to "hello" again, the test automatically runs again.

8.1. Commands for controlling continuous testing

You can use hotkey commands on your keyboard to control your options for continuous testing. To view the full list of commands, press 'h' on your keyboard. The following options are available:

Command Description

r

Re-run all tests.

f

Re-run all tests that failed.

b

Toggle 'broken only' mode. Only the tests that were failing previously are run, even if other tests are affected by your code changes. This option might be useful if you change code that is used by many tests, but you want to only review the failed tests.

v

Print output detailing test failures from the last test run to the console. This option might be useful if there was a considerable amount of console output since the last test run.

p

Pause running tests temporarily. This might be useful if you are making a lot of code changes, but do not want to get test feedback until you finish making the changes.

q

Exit continuous testing.

o

Print test output to the console. This is disabled by default. When test output is disabled, the output is filtered and saved, but not displayed on the console. You can view the test output on the Development UI.

i

Toggle instrumentation-based reload. Using this option does not directly affect testing, but does allow live reload to occur. This might be useful to avoid a restart if a change does not affect the structure of a class.

l

Toggle live reload. Using this option does not directly affect testing, but enables you to turn live reloading on and off.

s

Force restart. Using this option, you can force a scan of changed files and a live reload that includes the changes. Note that even if there are no code changes and live reload is disabled, the application still restarts.

9. Packaging and running the Quarkus Getting Started application

After you compile your Quarkus Getting Started project, you can package it in a JAR file and run it from the command line.

The command that you use to package and run your Quarkus Getting Started application depends on the developer tool that you have installed on the machine.

Prerequisites
  • You have compiled the Quarkus Getting Started project.

Procedure
  1. Go to the getting-started project directory.

  2. To package your Quarkus Getting Started project, use one of the following methods, depending on the developer tool that you intend to use:

    • If you prefer to use Apache Maven, enter the following command:

      mvn package
    • If you prefer to use the Quarkus command-line interface (CLI), enter the following command:

      quarkus build
    • If you prefer to use the Maven wrapper, enter the following command:

      ./mvnw package

      This command produces the following JAR files in the /target directory:

      • getting-started-1.0-0-SNAPSHOT.jar: Contains the classes and resources of the projects. This is the regular artifact produced by the Maven build.

      • quarkus-app/quarkus-run.jar: Is an executable JAR file. This file is not an uber-JAR file. The dependencies are copied into the target/quarkus-app/lib directory.

  3. To start your application, enter the following command:

    java -jar target/quarkus-app/quarkus-run.jar
    • Before running the application, ensure that you stop development mode, (press CTRL+C), or you will have a port conflict.

    • The Class-Path entry of the MANIFEST.MF file from the quarkus-run.jar file explicitly lists the JAR files from the lib directory. If you want to deploy your application from another location, you must copy the quarkus-run.jar file and the lib directory.

10. JVM and native building modes

The following section describes compiling a classic JVM application and compiling a native application with Mandrel or GraalVM’s native-image tool.

10.1. Compiling an application as a classic JVM application

You can compile your application as a JVM application. This option is based on the quarkus.package.type configuration property and generates one of the following files:

  • fast-jar: A JAR file that is optimized for Quarkus and the default configuration option. Results in slightly faster startup times and slightly reduced memory usage.

  • legacy-jar: A typical JAR file.

  • uber-jar: A single standalone JAR file.

    These JAR files work on all operating systems and build much faster than native images.

10.2. Compiling an application into a native image

You can compile your application into a native image. To do so, you set the quarkus.package.type configuration property to native.

With this property, you create an executable binary file that is compiled specifically for an operating system of your choice, such as an .exe file for Windows. These files have faster start times and lesser RAM consumption than JAVA JAR files, but their compilation takes several minutes. In addition, the maximum throughput achievable by using a native binary is lower than a regular JVM application because the profile-guided optimizations are missing.

  • Using Mandrel

    Mandrel is a specialized distribution of GraalVM for Red Hat build of Quarkus and also the recommended approach for building native executables that target Linux containerized environments. While the Mandrel approach is perfect for embedding the compilation output in a containerized environment, only a Linux64 bit native executable is provided. Therefore, an outcome such as .exe is not an option.

    Mandrel users are encouraged to use containers to build their native executables.

    To use the official Mandrel image to compile an application into native mode using a local installation of Docker or Podman, enter the mvn package command with the following properties:

    -Dquarkus.package.type=native
    -Dquarkus.native.container-build=true
    -Dquarkus.native.builder-image=quay.io/quarkus/ubi-quarkus-mandrel:{MandrelVersion}-{JDK-ver-other}
  • Using GraalVM

    Because Mandrel does not support macOS and Windows platforms, you can use Oracle GraalVM to build native executables on these operating systems.

    You can also build native executables by using Oracle GraalVM directly on bare metal Linux or Windows distributions. For more information about this process, see the Oracle GraalVM README and release notes.

    For information about how to build a native executable by using Oracle GraalVM, see Compiling your Quarkus applications to native executables.

Additional resources

11. Packaging and running the Quarkus Getting Started application in native mode

In native mode, the output from the application builds is a platform-dependent native binary file rather than a compress or archive JAR file. For more information about how native mode differs from the JVM, see the JVM and native building modes chapter of the Getting Started guide.

Prerequisites
  • You have installed OpenJDK 11 or 17 installed and set the JAVA_HOME environment variable to specify the location of the Java SDK.

  • You have installed Apache Maven 3.8.x, where x is 6 or later.

  • You have a working C development environment.

  • You have a working container runtime, such as Docker or Podman.

  • Optional: If you want to use the Quarkus command-line interface (CLI), ensure that it is installed.

    • For instructions on how to install the Quarkus CLI, refer to the community-specific information at Quarkus CLI.

  • You have cloned and compiled the Quarkus Getting Started project.

  • You have downloaded and installed a community or enterprise edition of GraalVM.

    • To download and install a community or an enterprise edition of GraalVM, refer to the official GraalVM Getting Started documentation.

    • Alternatively, use platform-specific install tools such as sdkman, homebrew, or scoop.

While you can use the community edition of GraalVM to complete all of the procedures in the Getting Started guide, the community edition of GraalVM is not supported in a Red Hat build of Quarkus production environment. For more information, see Compiling your Quarkus applications to native executables.

Procedure
  1. Configure the runtime environment by setting the GRAALVM_HOME environment variable to the GraalVM installation directory. For example:

    export GRAALVM_HOME=$HOME/Development/graalvm/
    • On macOS, point the variable to the Home sub-directory:

      export GRAALVM_HOME=$HOME/Development/graalvm/Contents/Home/
    • On Windows, set your environment variables by using the Control Panel.

  2. Install the native-image tool:

    ${GRAALVM_HOME}/bin/gu install native-image
  3. Set the JAVA_HOME environment variable to the GraalVM installation directory:

    export JAVA_HOME=${GRAALVM_HOME}
  4. Add the GraalVM bin directory to the path:

    export PATH=${GRAALVM_HOME}/bin:$PATH
  5. Go to the Getting Started project folder:

    cd getting-started
  6. Compile a native image by using one of the following ways:

    • Using Maven:

      mvn clean package -Pnative
    • Using the Quarkus CLI:

      quarkus build --native
Verification
  1. Start the application:

    ./target/getting-started-1.0.0-SNAPSHOT-runner
  2. Observe the log message and verify that it contains the word native:

    2022-03-04 09:51:51,505 INFO [io.quarkus] (main) getting-started 1.0.0-SNAPSHOT native (powered by Quarkus 2.7.3.Final) started in 0.043s. Listening on: http://0.0.0.0:8080
Additional resources

12. Additional resources