Spring Boot:メインクラスの設定

Spring Boot:メインクラスの構成

1. 概要

このクイックチュートリアルでは、MavenおよびGradleを介してSpring Bootアプリケーションへのエントリポイントを定義するさまざまな方法を提供します。

Spring Bootアプリケーションのメインクラスは、SpringApplicationContextを起動するpublic static void main()メソッドを含むクラスです。 By default, if the main class isn’t explicitly specified, Spring will search for one in the classpath at compile time and fail to start if none or multiple of them are found.

従来のJavaアプリケーションとは異なり、このチュートリアルで説明するメインクラスは、結果のJARまたはWARファイルのMETA-INF / MANIFEST.MFのMain-Classメタデータプロパティとして表示されません。

Spring Bootは、アーティファクトのMain-Classメタデータプロパティがorg.springframework.boot.loader.JarLauncher (またはWarLauncher に設定されていることを想定しています。これは、メインクラスをJavaコマンドに直接渡すことを意味します。 lineはSpringBootアプリケーションを正しく起動しません。

マニフェストの例は次のとおりです。

Manifest-Version: 1.0
Start-Class: org.example.DemoApplication
Main-Class: org.springframework.boot.loader.JarLauncher

代わりに、アプリケーションを起動するためにJarLauncherによって評価されるマニフェストでStart-Classプロパティを定義する必要があります。

MavenとGradleを使用してこのプロパティを制御する方法を見てみましょう。

2. メーベン

メインクラスは、pom.xmlのプロパティセクションでa start-class要素として定義できます。


      
      org.example.DemoApplication

this property will only be evaluated if we also add the spring-boot-starter-parentは、pom.xml<parent>として使用されることに注意してください。

または、pom.xmlのプラグインセクションにあるthe main class can be defined as the mainClass element of the spring-boot-maven-plugin


    
        
            org.springframework.boot
            spring-boot-maven-plugin
            
                org.example.DemoApplication
            
        
    

このMaven構成の例は、over on GitHub.にあります。

3. Gradle

Spring Boot Gradle pluginを使用している場合、メインクラスを指定できるorg.springframework.boot から継承されたいくつかの構成があります。

プロジェクトのGradleファイルでは、mainClassNamewithin springBoot configuration blockとして定義できます。 ここで行われたこの変更は、bootRunおよびbootJarタスクによって取得されます。

springBoot {
    mainClassName = 'org.example.DemoApplication'
}

または、メインクラスをbootJar GradleタスクのmainClassNameプロパティとして定義することもできます。

bootJar {
    mainClassName = 'org.example.DemoApplication'
}

または、bootJarタスクのマニフェスト属性として:

bootJar {
    manifest {
    attributes 'Start-Class': 'org.example.DemoApplication'
    }
}

bootJar構成ブロックで指定されたメインクラスは、タスク自体が生成するJARにのみ影響することに注意してください。 この変更は、bootRunなどの他のSpring BootGradleタスクの動作には影響しません。

ボーナスとして、Gradle application pluginがプロジェクトに適用される場合、mainClassName can be defined as a global property:

mainClassName = 'org.example.DemoApplication'

これらのGradle構成の例を見つけることができますover on GitHub.

4. CLIを使用する

コマンドラインインターフェイスを介してメインクラスを指定することもできます。

Spring Bootのorg.springframework.boot.loader.PropertiesLauncherにはJVM引数が付属しており、loader.mainと呼ばれる論理メインクラスをオーバーライドできます。

java -cp bootApp.jar -Dloader.main=org.example.DemoApplication org.springframework.boot.loader.PropertiesLauncher

5. 結論

Spring Bootアプリケーションへのエントリポイントを指定する方法はいくつかあります。 これらの構成はすべて、JARまたはWARファイルのマニフェストを変更するための異なる方法にすぎないことを知っておくことが重要です。

実用的なコード例は、herehereにあります。