初めてのアプリケーションの作成
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 を使用するかは、 |
2. プロジェクトの開始
新しい Quarkus プロジェクトを作成する最も簡単な方法は、ターミナルを開いて以下のコマンドを実行することです。
Windowsユーザーの場合:
-
cmdを使用する場合、(バックスラッシュ
\を使用せず、すべてを同じ行に書かないでください)。 -
Powershellを使用する場合は、
-Dパラメータを二重引用符で囲んでください。例:"-DprojectArtifactId=getting-started"
./getting-started に以下の内容が生成されます。
-
Maven の構造
-
an
org.acme.GreetingResourceREST endpoint exposed on/hello -
関連するユニットテスト
-
アプリケーション起動後に
http://localhost:8080でアクセス可能な Web ページ -
src/main/dockerに配置されるnativeとjvmの両方のモード用の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
./mvnw quarkus:dev
./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" で自動的に改行が追加されるようにします。この例では |
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
./mvnw quarkus:dev
./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つのテストの依存関係が示されています。
<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>
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
|
テストポートは、 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
./mvnw install
./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:
-
Your Second Quarkus Application — add a database without installing one, using Dev Services
-
Building a Native Executable — compile to a native binary and package it in a container
-
Getting Started with Quarkus and Kafka — build event-driven and streaming applications with Quarkus and Apache Kafka
-
Tooling Guide — IDE setup, scaffolding, and development mode tips
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