コマンドライン引数をつけて実行する

はじめに

application.propertiesやapplication.ymlでプロパティを設定していたが、コマンドライン引数をつかっても設定できるので試したメモです

messageというキー、nihao0という値で設定する

IntelliJ

Program argumentsにプロパティを設定する

f:id:fjswkun:20220325101333p:plain f:id:fjswkun:20220325101336p:plain

messageを取得するコードを書き、Runで実行すると確認できる

package com.example.properties

import org.springframework.beans.factory.annotation.Value
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController

@RestController("/")
class HelloController(
    @Value("\${message}")
    val message: String
) {
    @GetMapping
    fun hello(): String {
        return message
    }
}

結果 f:id:fjswkun:20220325101701p:plain

jarファイルから起動

ビルドしてjarファイルを作る際にmessageが設定されてなくてエラーになる。 application.ymlなどでデフォルト値を設定しておくと良い。

java -jar build/libs/properties-0.0.1-SNAPSHOT.jar --massage=nihao0