🔥 FREE PRO OFFER Linkage.page Pro Version is 100% Free of Cost till 31 December, 2026! Claim Free Pro

GraalVM

CDI を使用した Quarkus での依存性インジェクション: ArC、スコープ、修飾子、ビルドタイム インジェクション

CDI を使用した Quarkus での依存性インジェクション: ArC、スコープ、修飾子、ビルドタイム インジェクション

依存関係の注入 (DI) は、最新のエンタープライズ Java アプリケーション開発の基盤です。長年にわたり、Java 開発者は Spring IoC (制御の反転) または Hibernate Weld や OpenWebBeans などの標準の Jakarta EE CDI (コンテキストと依存関係の挿入) コンテナーに依存して、コンポーネントのライフサイクルを分離し、サービスの依存関係を管理し、構成プロパティを挿入してきました。 しかし、エンタープライズ アプリケーションがクラウドネイティブ マイクロサービス、Docker と Kubernetes によるコンテナ化、およびサーバーレス実行モデル (AWS Lambda、Knative) に移行するにつれて、従来の依存関係注入コンテナーには、重いランタイム リフレクションと高いメモリ オーバーヘッドという重大な欠陥が露呈しました。 Quarkus とその軽量 CDI エンジン ArC を登場させます。 Kubernetes と GraalVM のネイティブ コンパイル用にゼロから構築された Quarkus は、リフレクション、クラスパス スキャン、Bean グラフのワイヤリングをアプリケーションの実行時からビルド時に移行することで、依存関係の注入を再定義します。 この詳細ガイドでは、CDI を使用した Quarkus での依存性注入について詳しく説明し、ArC コンテナの内部機構、CDI スコープ、カスタム修飾子、プロデューサー、インターセプター、イベント駆動型オブザーバー、プログラムによるルックアップ、および高パフォーマンスのクラウドネイティブ Java アプリケーションを作成するためのベスト プラクティスについて説明します。
Java Quarkus CDI ArC Dependency Injection Microservices Cloud Native Software Architecture GraalVM
Java QuarkusによるREST APIの構築:高性能、リアクティブ、クラウドネイティブ完全ガイド

Java QuarkusによるREST APIの構築:高性能、リアクティブ、クラウドネイティブ完全ガイド

現代のエンタープライズソフトウェアエンジニアリングにおいて、RESTful APIの構築はバックエンド開発の基盤です。何年もの間、JavaデベロッパーはSpring BootやJakarta EEなどの従来フレームワークに依存してきました。 そこで登場したのがQuarkusです。OpenJDK HotSpotとGraalVMのために設計されたSupersonic Subatomic Javaフレームワークです。 1. なぜJava REST APIにQuarkusを選ぶのか? A. RESTEasy Reactive パラダイム B. Dev Services & 設定不要のライブコーディング 2. Quarkus REST APIのアーキテクチャ 3. プロジェクトの初期化と依存関係 mvn io.quarkus.platform:quarkus-maven-plugin:3.15.0:create \ -DprojectGroupId=com.ghaznix.api \ -DprojectArtifactId=quarkus-product-api \ -DclassName="com.ghaznix.api.ProductResource" \ -Dpath="/api/products" \ -Dextensions="resteasy-reactive-jackson,hibernate-orm-panache,jdbc-postgresql,hibernate-validator,smallrye-openapi" 4. アプリケーションプロパティの設定 # Application Configuration quarkus.application.name=quarkus-product-api quarkus.http.port=8080 # Database Configuration (Dev Services will override in dev mode automatically) quarkus.datasource.db-kind=postgresql quarkus.datasource.username=postgres quarkus.datasource.password=secret quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/product_db # Hibernate ORM Configuration quarkus.hibernate-orm.database.generation=drop-and-create quarkus.hibernate-orm.log.sql=true # Swagger UI & OpenAPI Path quarkus.swagger-ui.always-include=true quarkus.swagger-ui.path=/swagger-ui 5. ドメインモデルとPanacheによるActive Record package com.ghaznix.api; import io.quarkus.hibernate.orm.panache.PanacheEntity; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Table; import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import java.math.BigDecimal; import java.util.List; @Entity @Table(name = "products") public class Product extends PanacheEntity { @NotBlank(message = "Product name cannot be blank") @Column(nullable = false) public String name; @Column(length = 1000) public String description; @NotNull(message = "Price is required") @Min(value = 0, message = "Price must be non-negative") @Column(nullable = false) public BigDecimal price; @Column(nullable = false) public Integer stockQuantity; public String category; // Static Finder Utility Methods powered by Panache public static List<Product> findByCategory(String category) { return list("category", category); } public static List<Product> findAvailableProducts() { return list("stockQuantity > 0"); } } 6. プロダクション級RESTエンドポイントの構築 package com.ghaznix.api; import io.quarkus.panache.common.Page; import io.quarkus.panache.common.Sort; import jakarta.transaction.Transactional; import jakarta.validation.Valid; import jakarta.ws.rs.*; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import org.eclipse.microprofile.openapi.annotations.Operation; import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; import org.eclipse.microprofile.openapi.annotations.tags.Tag; import java.net.URI; import java.util.List; @Path("/api/products") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Tag(name = "Product REST API", description = "Operations for managing catalog products") public class ProductResource { @GET @Operation(summary = "Get all products with pagination") @APIResponse(responseCode = "200", description = "List of products retrieved successfully") public List<Product> getAllProducts( @QueryParam("page") @DefaultValue("0") int pageIndex, @QueryParam("size") @DefaultValue("10") int pageSize, @QueryParam("sort") @DefaultValue("name") String sortBy) { return Product.findAll(Sort.by(sortBy)) .page(Page.of(pageIndex, pageSize)) .list(); } @GET @Path("/{id}") @Operation(summary = "Get product by ID") @APIResponse(responseCode = "200", description = "Product details found") @APIResponse(responseCode = "404", description = "Product not found") public Product getProductById(@PathParam("id") Long id) { Product product = Product.findById(id); if (product == null) { throw new NotFoundException("Product with ID " + id + " does not exist."); } return product; } @POST @Transactional @Operation(summary = "Create a new product") @APIResponse(responseCode = "201", description = "Product created successfully") @APIResponse(responseCode = "400", description = "Invalid request payload") public Response createProduct(@Valid Product product) { product.persist(); return Response.created(URI.create("/api/products/" + product.id)) .entity(product) .build(); } @PUT @Path("/{id}") @Transactional @Operation(summary = "Update an existing product") @APIResponse(responseCode = "200", description = "Product updated") @APIResponse(responseCode = "404", description = "Product ID not found") public Product updateProduct(@PathParam("id") Long id, @Valid Product updatedProduct) { Product entity = Product.findById(id); if (entity == null) { throw new NotFoundException("Product with ID " + id + " not found."); } entity.name = updatedProduct.name; entity.description = updatedProduct.description; entity.price = updatedProduct.price; entity.stockQuantity = updatedProduct.stockQuantity; entity.category = updatedProduct.category; return entity; } @DELETE @Path("/{id}") @Transactional @Operation(summary = "Delete a product by ID") @APIResponse(responseCode = "204", description = "Product deleted successfully") @APIResponse(responseCode = "404", description = "Product ID not found") public Response deleteProduct(@PathParam("id") Long id) { boolean deleted = Product.deleteById(id); if (!deleted) { throw new NotFoundException("Product with ID " + id + " not found."); } return Response.noContent().build(); } } 7. リアクティブRESTエンドポイント vs ブロッキング実行 import io.smallrye.mutiny.Uni; import io.smallrye.mutiny.Multi; @GET @Path("/reactive/{id}") public Uni<Product> getProductReactive(@PathParam("id") Long id) { return Product.<Product>findByIdAsync(id) .onItem().ifNull().failWith(new NotFoundException("Product not found")); } @GET @Path("/stream") @Produces(MediaType.SERVER_SENT_EVENTS) public Multi<Product> streamProducts() { return Product.streamAll(); } 8. グローバル例外処理とエラー標準 package com.ghaznix.api.exception; import jakarta.ws.rs.NotFoundException; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.ext.ExceptionMapper; import jakarta.ws.rs.ext.Provider; import java.time.Instant; import java.util.HashMap; import java.util.Map; @Provider public class GlobalExceptionMapper implements ExceptionMapper<Exception> { @Override public Response toResponse(Exception exception) { Map<String, Object> errorPayload = new HashMap<>(); errorPayload.put("timestamp", Instant.now().toString()); if (exception instanceof NotFoundException) { errorPayload.put("status", 404); errorPayload.put("error", "Not Found"); errorPayload.put("message", exception.getMessage()); return Response.status(Response.Status.NOT_FOUND) .entity(errorPayload) .type(MediaType.APPLICATION_JSON) .build(); } errorPayload.put("status", 500); errorPayload.put("error", "Internal Server Error"); errorPayload.put("message", exception.getMessage()); return Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(errorPayload) .type(MediaType.APPLICATION_JSON) .build(); } } 9. @QuarkusTestとREST Assuredによる自動テスト package com.ghaznix.api; import io.quarkus.test.junit.QuarkusTest; import io.restassured.http.ContentType; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.*; @QuarkusTest public class ProductResourceTest { @Test public void testGetAllProductsEndpoint() { given() .when().get("/api/products") .then() .statusCode(200) .contentType(ContentType.JSON); } @Test public void testCreateAndGetProduct() { Product product = new Product(); product.name = "Gaming Laptop"; product.description = "High-performance GPU laptop"; product.price = new java.math.BigDecimal("1499.99"); product.stockQuantity = 15; product.category = "Electronics"; // Test POST Endpoint Integer createdId = given() .contentType(ContentType.JSON) .body(product) .when().post("/api/products") .then() .statusCode(201) .body("name", equalTo("Gaming Laptop")) .extract().path("id"); // Test GET Endpoint by ID given() .pathParam("id", createdId) .when().get("/api/products/{id}") .then() .statusCode(200) .body("category", equalTo("Electronics")); } } ./mvnw test 10. パッケージングとGraalVMネイティブバイナリへのコンパイル ./mvnw quarkus:dev ./mvnw package java -jar target/quarkus-app/quarkus-run.jar ./mvnw package -Dnative -Dquarkus.native.container-build=true ./target/quarkus-product-api-1.0.0-runner 2026-09-21 22:30:00,014 INFO [io.quarkus] (main) quarkus-product-api 1.0.0-runner native (powered by Quarkus 3.15.0) started in 0.018s. Listening on: http://0.0.0.0:8080 11. パフォーマンスベンチマーク:Quarkus vs Spring Boot ベンチマーク指標 Spring Boot (JVM) Quarkus (OpenJDK JVM) Quarkus (GraalVM Native) 改善効果 起動時間 (コールドスタート) 3.82 秒 1.18 秒 0.015 秒 254倍高速 メモリ消費量 (RSS) 184 MB 108 MB 28 MB 84%削減 12. 結論とベストプラクティス Ghaznix Blog.
Java Quarkus REST API マイクロサービス GraalVM リアクティブプログラミング Hibernate Panache クラウドネイティブ ソフトウェアアーキテクチャ
Quarkus と Spring Boot: どの Java フレームワークを選択する必要がありますか?

Quarkus と Spring Boot: どの Java フレームワークを選択する必要がありますか?

10 年以上にわたり、Spring Boot はエンタープライズ Java アプリケーションを構築するための事実上の標準として君臨してきました。 Java は、その豊富なエコシステム、構成より規約のパラ​​ダイム、堅牢な依存関係注入エンジン、および大規模なコミュニティ サポートにより、世界中のバックエンド システムの基盤となっています。 しかし、クラウドネイティブ アーキテクチャ、Kubernetes オーケストレーション、Docker コンテナ化、サーバーレス実行 (AWS Lambda、Knative) への移行により、メモリ効率、インスタント スケーリング、コールドスタート レイテンシといった新しい技術的課題がバックエンド インフラストラクチャに導入されました。 従来の Java フレームワークは、長時間稼働するモノリシック サーバー向けに設計されており、元々は一時的なコンテナ化環境向けに設計されたものではありませんでした。マイクロサービスが Kubernetes 上で 0 から 50 のインスタンスまで水平にスケールしたり、短期間のサーバーレス関数として実行したりする場合、200MB 以上のヒープ メモリを消費しながら、Java 仮想マシン (JVM) プロセスが起動するまで 3 ~ 10 秒待機すると、運用上および財務上のハンディキャップが生じます。 Quarkus は、特に GraalVM および OpenJDK HotSpot 向けに Java を調整するためにゼロから構築された Kubernetes ネイティブ Java フレームワークです。 「Supersonic Subatomic Java」 と呼ばれる Quarkus は、Java コードのコンパイル、起動、実行方法を根本的に再定義します。
Java Quarkus Spring Boot GraalVM Microservices Cloud Native Kubernetes JVM Software Architecture
Quarkus の紹介: Java 開発者が Supersonic Java に移行する理由

Quarkus の紹介: Java 開発者が Supersonic Java に移行する理由

30 年近くにわたり、Java はエンタープライズ ソフトウェア開発の主流となってきました。その豊富なエコシステム、堅牢なオブジェクト指向基盤、Java 仮想マシン (JVM) によるプラットフォームの独立性、および Spring Boot などの歴戦のフレームワークにより、バックエンド インフラストラクチャの明白な王者となりました。 しかし、クラウドネイティブ アーキテクチャ、Kubernetes オーケストレーション、コンテナ化 (Docker)、サーバーレス コンピューティング (AWS Lambda、Knative) への移行により、高いメモリ オーバーヘッドと遅い起動時間という、従来の Java アプリケーション フレームワークの深刻な脆弱性が明らかになりました。 トラフィックの急増に対応してマイクロサービスがレプリカを 0 から 100 まで水平にスケールする必要がある場合、またはサーバーレス関数がオンデマンドで実行される場合、Java プロセスの起動を 3 ~ 10 秒待つことは許容できません。最新のクラウド インフラストラクチャでは、即時起動と軽量メモリ消費が求められます。これらの特性は従来、Go、Rust、Node.js などの言語に限定されていました。 Quarkus は、GraalVM および OpenJDK HotSpot 向けに特別に設計された Kubernetes ネイティブ Java フレームワークです。 「Supersonic Subatomic Java」 とも呼ばれる Quarkus は、Java アプリケーションのコンパイル、ブート、実行方法を根本的に再設計します。 この詳細なガイドでは、Java 開発者が Quarkus を採用する理由、Quarkus が 1 秒未満の起動時間とマイクロメモリの使用量をどのように達成するか、ビルド時間の最適化 のアーキテクチャの仕組み、および Quarkus を使用して Java で本番環境に対応したリアクティブ マイクロサービスを構築する方法について説明します。
Java Quarkus GraalVM Microservices Cloud Native Spring Boot JVM Software Architecture Serverless