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分

  • IDE

  • JDK 17+がインストールされ、 JAVA_HOME が適切に設定されていること

  • Apache Maven 3.9.16

  • 使用したい場合は、 Quarkus CLI

Maven が意図した Java を使用していることの確認

複数の JDK がインストールされている場合、 Maven が意図した java を利用するとは限らず、予期しない結果になる可能性があります。 Maven がどの JDK を使用するかは、 mvn --version を実行することで確認することができます。

2. プロジェクトの開始

新しい Quarkus プロジェクトを作成する最も簡単な方法は、ターミナルを開いて以下のコマンドを実行することです。

コマンドラインインタフェース
quarkus create app org.acme:getting-started \
    --extension='rest'
cd getting-started

Gradleプロジェクトを作成するには、 --gradle または --gradle-kotlin-dsl オプションを追加します。

Quarkus CLIのインストールと使用方法の詳細については、 Quarkus CLI ガイドを参照してください。

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

Gradleプロジェクトを作成するには、 -DbuildTool=gradle または -DbuildTool=gradle-kotlin-dsl オプションを追加します。

Windowsユーザーの場合:

  • cmdを使用する場合、(バックスラッシュ \ を使用せず、すべてを同じ行に書かないでください)。

  • Powershellを使用する場合は、 -D パラメータを二重引用符で囲んでください。例: "-DprojectArtifactId=getting-started"

./getting-started に以下の内容が生成されます。

  • Maven の構造

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

  • 関連するユニットテスト

  • アプリケーション起動後に http://localhost:8080 でアクセス可能な Web ページ

  • src/main/docker に配置される nativejvm の両方のモード用の Dockerfile ファイルの例

  • アプリケーションの設定ファイル

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/getting/started/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";
    }
}

これは非常にシンプルなRESTエンドポイントで、"/hello "へのリクエストに対して "Hello from Quarkus REST "を返します。

3. アプリケーションの実行

ここまでで、アプリケーションを実行する準備が整いました。

コマンドラインインタフェース
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" を使用して、結果とプロンプトが1行で表示されてしまうことを防止しています。

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 の依存性注入は、Quarkus のアーキテクチャに合わせて調整された CDI ベースの依存性注入ソリューションである ArC をベースにしています。 CDI が初めての方は、 CDI入門 ガイドをお読みになることをお勧めします。

Quarkus は CDI 機能のサブセットのみを実装しており、非標準の機能や特定の API が付属しています。詳細は、 コンテキストと依存性注入ガイド を参照してください。

ArC は quarkus-rest の依存関係として提供されているので、既に手元にあります。

アプリケーションを変更してコンパニオン Bean を追加してみましょう。 以下の内容で src/main/java/org/acme/getting/started/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";
    }
}

アプリケーションを停止しなくても、ライブリロード機能によって変更が自動的にデプロイされますが、アプリケーションを停止した場合は、次のようにアプリケーションを再起動します。

コマンドラインインタフェース
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.

このため、Maven の場合、デフォルトのバージョンは JUnit をサポートしていないため、 Surefire Maven Plugin のバージョンを設定する必要があります。

<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 からカスタム設定が適用されることを確認します (存在する場合)。

生成されたプロジェクトには簡単なテストが含まれています。 src/test/java/org/acme/getting/started/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 レスポンスのステータスコードと内容を確認します。

これらのテストでは RestAssured を使用していますが、普段利用しているライブラリーを自由に使用することも可能です。

これらは 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;

テストポートは、 quarkus.http.test-port 設定プロパティーで制御できます。

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. パッケージ化とアプリケーションの実行

このアプリケーションは、以下の方法でパッケージ化されています。

コマンドラインインタフェース
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/.

アプリケーションを実行するには、次のようにします: 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

関連コンテンツ