はじめに
Kotlinで、となると絶妙に情報が少ないので書いてみました。
前提
- spring-boot-starter 2.4.x
- Kotlin 1.4.x
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.stereotype.Component
@Component
@ConditionalOnProperty(value = ["exec"], havingValue = "sample")
class SampleRunner : ApplicationRunner {
override fun run(args: ApplicationArguments?) {
// 何かしらの処理をする
}
}
正常終了(万事うまくいったケース)
そのまま終了したら終了コード 0(正常)です。
異常終了(もう続行不能なので処理中断するケース1)
処理ロジック中でお好みのExceptionをThrowして異常終了させれば終了コード 1(異常終了)です。
ログにExceptionのStackTraceが出るので、どこでエラーが出たか分かります。
異常終了(もう続行不能なので処理中断するケース2)
終了コードのバリエーションが1だけじゃ足りない!という場合は、
特定の終了コードを返してくれるExceptionを自作しましょう。
(例:データの処理エラーは1で出社対応するけど、外部アクセスエラーでリトライしたい場合は2を返して、10分後にリトライしたい)
import org.springframework.boot.ExitCodeGenerator
class AbcException(message: String) : Exception(message), ExitCodeGenerator {
override fun getExitCode(): Int {
return 2
}
}
こちらも、ログにExceptionのStackTraceが出るので、どこでエラーが出たか分かります。
警告終了(とりあえず全データ処理したんだけど一部失敗しちゃったケース)
SampleRunnerまで返ってきたけど、処理結果が万事OKというわけではない。。終了コードは0以外にしたい場合です。
class SampleRunner : ApplicationRunner {
override fun run(args: ApplicationArguments?) {
// 何かしらの処理をする
val sampleStatus = "warning" // 実際は処理結果で判定してください!
if( sampleStatus != "warning") {
exitProcess(3)
}
}
}
こちらは、ログにStackTraceは出ません。なぜ異常終了したかは別途ログ出力しましょう。
おわり
夏は気づいたらすごい(遅い)時間になっていてこわいですね。
上記のRunnerはたぶん -Dexec=sample
で動きます。