DEV Community

kaede
kaede

Posted on

1

Kotlin 基礎 Part 12 -- Gradle で作成した Spring アプリのビルドファイルを実行可能にする

why

Docker イメージを生成して ECR に push したかった。
そのために、Jar ファイルを実行可能な状態にする。


jar ファイルとは

https://docs.oracle.com/javase/jp/7/technotes/guides/jar/jarGuide.html

Java ARchive の略。
Java/Kotlin のアプリのビルド後の成果物。
Zip ファイルに近い仕様。
.zip に拡張子を変えればダブルクリップで開ける。

https://qiita.com/maple_syrup/items/a2f21fe356fa5f06bf44#jar%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%81%AE%E4%B8%80%E8%A6%A7%E8%A1%A8%E7%A4%BA

jar -tf コマンドで中身が見れる。
jar コマンドで実行できる。


結論

プロジェクトは spring302

 ./gradlew build 
Enter fullscreen mode Exit fullscreen mode

このコマンドでビルドする。

Image description

spring302-0.0.1-SNAPSHOT.jar
Enter fullscreen mode Exit fullscreen mode

すると、plain と plain ではない jar ファイルが生成される。

java -jar build/libs/spring302-0.0.1-SNAPSHOT.jar
Enter fullscreen mode Exit fullscreen mode

plain ではない jar ファイルを実行することで

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v3.0.2)


c.k.spring302.Spring302ApplicationKt     
: Started Spring302ApplicationKt in 4.151 seconds 
Enter fullscreen mode Exit fullscreen mode

Spring アプリが実行された。


原因

Kotlin で作ったプレーンな jar ファイルは実行できない。

Image description

IntelliJ のビルドボタンのクリックでは

  • {app}-{ver}-plain.jar

これしか生成されない。

一方、.gradlew/ build コマンドで実行すると

  • {app}-{ver}.jar
  • {app}-{ver}-plain.jar

これらが両方出力される。

IntelliJ ではプレーンではない jar ファイルが出力できないのが原因。


まとめ

IntelliJ で Kotlin Spring Gradle のアプリをビルドして実行するためには

  1. Spring Initailizer で Gradle x Kotlin でプロジェクト生成
  2. ./gradlew build でビルド
  3. java -jar build/libs/{projectName}-{version}.jar で実行

これで実行できる。

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.