The English version of quarkus.io is the official project site. Translated sites are community supported on a best-effort basis.

创建你的第一个应用程序

In this guide, you’ll create a REST endpoint, see live coding in action, add a service with dependency injection, and write tests. You won’t write any boilerplate, and you won’t have to restart the app, not even once.

Already ran the Quick Start? Skip to 使用注入法.

1. 先决条件

完成这个指南,你需要:

  • 大概15分钟

  • 编辑器

  • JDK 17+ installed with JAVA_HOME configured appropriately

  • Apache Maven 3.9.16

  • 如果你愿意的话,还可以选择使用Quarkus CLI

验证Maven是否使用了你期望的Java版本

If you have multiple JDK’s installed, it is not certain Maven will pick up the expected java and you could end up with unexpected results. You can verify which JDK Maven uses by running mvn --version.

2. 创建项目

创建一个新的Quarkus项目最简单的方法是打开终端并运行以下命令:

CLI
quarkus create app org.acme:getting-started \
    --extension='rest'
cd getting-started

创建Grade项目,请添加 --gradle 或者 --gradle-kotlin-dsl 参数。

For more information about how to install and use the Quarkus CLI, see the Quarkus CLI guide.

Maven
mvn io.quarkus.platform:quarkus-maven-plugin:3.37.0:create \
    -DprojectGroupId=org.acme \
    -DprojectArtifactId=getting-started \
    -Dextensions='rest'
cd getting-started

创建Grade项目,请添加 -DbuildTool=gradle 或者 -DbuildTool=gradle-kotlin-dsl 参数。

For Windows users:

  • If using cmd, (don’t use backward slash \ and put everything on the same line)

  • If using Powershell, wrap -D parameters in double quotes e.g. "-DprojectArtifactId=getting-started"

它在 ./getting-started 中产生了以下内容:

  • Maven的结构

  • an org.acme.GreetingResource REST endpoint exposed on /hello

  • 相关的单元测试

  • 启动应用程序后,可以通过 http://localhost:8080 访问的登陆页面

  • 示例 Dockerfile 文件,用于 nativejvm 两种模式,在 src/main/docker

  • 应用程序的配置文件

Look at the generated pom.xml. It imports the Quarkus BOM (quarkus-bom), so you can omit the version of Quarkus dependencies in your project. It also uses the quarkus-maven-plugin, which is responsible for packaging the application and providing development mode.

2.1. The REST endpoint

在项目创建过程中, src/main/java/org/acme/GreetingResource.java 文件已被创建,其内容如下:

package org.acme;

import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;

@Path("/hello")
public class GreetingResource {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String hello() {
        return "Hello from Quarkus REST";
    }
}

It’s a very simple REST endpoint, returning "Hello from Quarkus REST" to requests on "/hello".

3. 运行应用程序

现在我们已经准备好运行我们的应用程序:

CLI
quarkus dev
Maven
./mvnw quarkus:dev
Gradle
./gradlew --console=plain quarkusDev
...
__  ____  __  _____   ___  __ ____  ______
 --/ __ \/ / / / _ | / _ \/ //_/ / / / __/
 -/ /_/ / /_/ / __ |/ , _/ ,< / /_/ /\ \
--\___\_\____/_/ |_/_/|_/_/|_|\____/___/
INFO  [io.quarkus] (Quarkus Main Thread) getting-started 1.0.0-SNAPSHOT on JVM (powered by Quarkus {quarkus-version}) started in 0.968s. Listening on: http://localhost:8080
INFO  [io.quarkus] (Quarkus Main Thread) Profile dev activated. Live Coding activated.
INFO  [io.quarkus] (Quarkus Main Thread) Installed features: [cdi, rest, smallrye-context-propagation, vertx]

一旦启动,你可以发送请求到提供服务的端点。

$ curl -w "\n" http://localhost:8080/hello
Hello from Quarkus REST

Keep it running and enjoy the blazing fast hot-reload. If you really want shutdown the application, hit CTRL+C.

自动添加换行符 curl -w "\n"

我们在这个例子中使用 curl -w "\n" ,以避免你的终端打印出'%'或把结果和下一个命令提示符放在同一行。

4. Live coding

quarkus:dev runs Quarkus in development mode. Edit your Java files or resource files, save, and refresh your browser, changes take effect immediately, no restart needed. If there are any issues with compilation or deployment an error page will let you know.

Try it: open src/main/java/org/acme/GreetingResource.java, change "Hello from Quarkus REST" to "Hola from Quarkus", save, and refresh http://localhost:8080/hello. Then, switch back to "Hello from Quarkus REST", refresh again…​ changed again!

While dev mode is running, open the Dev UI, a dashboard where you can browse installed extensions, configuration, endpoints, and more, all live-updated as you code.

这也将在端口 5005 上监听调试器。如果你想在运行前等待调试器的连接,你可以在命令行中传递 -Dsuspend 。如果你根本不想要调试器,你可以使用 -Ddebug=false

5. 使用注入法

Quarkus中的依赖注入是基于ArC的,ArC是一个基于CDI的依赖注入解决方案,。如果你是CDI的新手,那么我们推荐你阅读 CDI简介 指南。

Quarkus只实现了CDI功能的一个子集,并且带有非标准的功能和特定的APIS,你可以在 Contexts和依赖注入指南 中了解更多。

ArC comes as a dependency of quarkus-rest so you already have it handy.

让我们修改应用程序并添加一个bean。创建 src/main/java/org/acme/GreetingService.java 文件,内容如下。

package org.acme;

import jakarta.enterprise.context.ApplicationScoped;

@ApplicationScoped
public class GreetingService {

    public String greeting(String name) {
        return "hello " + name;
    }

}

编辑 GreetingResource 类,注入 GreetingService ,并使用它创建一个新的端点:

package org.acme;

import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;

@Path("/hello")
public class GreetingResource {

    @Inject
    GreetingService service;

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    @Path("/greeting/{name}")
    public String greeting(String name) {
        return service.greeting(name);
    }

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String hello() {
        return "Hello from Quarkus REST";
    }
}

如果你停止了应用程序(请记住,你不必这样做,变化将由我们的实时重载功能自动部署),用以下方法重新启动应用程序:

CLI
quarkus dev
Maven
./mvnw quarkus:dev
Gradle
./gradlew --console=plain quarkusDev

然后检查端点是否按预期返回 hello quarkus :

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

6. 测试

All right, so far so good, but wouldn’t it be better with a few tests, just in case?

在生成的构建文件中,你可以看到2个测试依赖项:

pom.xml
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-junit</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <scope>test</scope>
</dependency>
build.gradle
testImplementation("io.quarkus:quarkus-junit")
testImplementation("io.rest-assured:rest-assured")

Quarkus supports JUnit tests.

Because of this, in the case of Maven, the version of the Surefire Maven Plugin must be set, as the default version does not support JUnit:

<plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>${surefire-plugin.version}</version>
    <configuration>
       <argLine>--add-opens java.base/java.lang=ALL-UNNAMED</argLine>
       <systemPropertyVariables>
          <java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
          <maven.home>${maven.home}</maven.home>
       </systemPropertyVariables>
    </configuration>
</plugin>

我们还设置了 java.util.logging 系统属性,以确保测试将使用正确的日志管理器和 maven.home ,以确保应用 ${maven.home}/conf/settings.xml 的自定义配置(如果有的话)。

生成的项目包含一个简单的测试。编辑 src/test/java/org/acme/GreetingResourceTest.java ,以匹配以下内容:

package org.acme;

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  (1)
class GreetingResourceTest {

    @Test
    void testHelloEndpoint() {
        given()
          .when().get("/hello")
          .then()
             .statusCode(200)    (2)
             .body(is("Hello from Quarkus REST"));
    }

    @Test
    void testGreetingEndpoint() {
        String uuid = UUID.randomUUID().toString();
        given()
          .pathParam("name", uuid)
          .when().get("/hello/greeting/{name}")
          .then()
            .statusCode(200)
            .body(is("hello " + uuid));
    }

}
1 By using the @QuarkusTest annotation, you instruct JUnit to start the application before the tests.
2 检查HTTP回应状态代码和内容

These tests use RestAssured, but feel free to use your favorite library.

你可以用Maven来运行这些:

./mvnw test

你也可以直接从你的IDE中运行测试(要确保你先停止了应用程序)。

By default, tests will run on port 8081 so as not to conflict with the running application. We automatically configure RestAssured to use this port.

If you want to use a different client you should use the @TestHTTPResource annotation to directly inject the URL of the tested application into a field on the test class. This field can be of the type String, URL or URI. This annotation can also be given a value for the test path. For example, if you want to test an endpoint mapped to /hello, you would just add the following to your @QuarkusTest test:

@TestHTTPResource("/hello")
URL testUrl;

The test port can be controlled via the quarkus.http.test-port config property.

6.1. Continuous testing

You can also have Quarkus run your tests automatically as you code. In the dev mode terminal, press r, and then Quarkus re-runs affected tests on every save, giving you instant feedback without leaving your editor. See the Continuous Testing guide for more details.

7. 应用程序打包和运行

该应用程序是用以下方式打包的:

CLI
quarkus build
Maven
./mvnw install
Gradle
./gradlew build

It produces the quarkus-app directory in /target, which contains the quarkus-run.jar file. This is a fast-jar, not an über-jar, the dependencies are copied into subdirectories of quarkus-app/lib/.

You can run the application using: java -jar target/quarkus-app/quarkus-run.jar.

If you want to deploy your application somewhere (typically in a container), you need to copy/deploy the whole quarkus-app directory.
在运行应用程序之前,不要忘记停止热重载模式(使用 CTRL+C ),否则你会有一个端口冲突。

8. 下一步做什么?

You now have a running Quarkus application with dependency injection and tests. Here’s where to go next:

8.1. 解决方案

You can find the completed example in the getting-started directory of the Quarkus quickstarts repository:

git clone https://github.com/quarkusio/quarkus-quickstarts.git

Related content