はじめに
Java + SpringBootでコマンドラインアプリを作るためのHow to記事は
Qiitaにもいくつかありますが、こちらはkotlinでやった場合です。
コード
main関数
SampleApplication.kt
@SpringBootApplication
class SampleApplication(val service: SampleService) : CommandLineRunner {
override fun run(vararg args: String?) {
// コマンドライン引数から取得
val name = args[0]!!.toString()
val mailAddress = args[1]!!.toString()
service.profileRegister(name, mailAddress)
}
}
fun main(args: Array<String>) {
SpringApplication.run(SampleApplication::class.java, *args)
}
テストコード(JUnit5)でrunが動かないようにする設定。
これをやらないとテストコード実施時に、SampleApplicationのrunが動いてしまうようです。
アノテーション@ExtendWith、@ContextConfigurationにて定義します。
SampleServiceTest.kt
@ExtendWith(SpringExtension::class)
@ContextConfiguration(classes = [SampleServiceTest::class],
initializers = [ConfigFileApplicationContextInitializer::class])
class SampleTest {
@Autowired
private lateinit var svc: SampleService
@Test
fun testProfileRegister() {
val resp = svc.profileRegister("Taro Yamada", "xxxxx@example.com")
assertThat(resp.name).isEqualTo("Taro Yamada")
assertThat(resp.mailAddress).isEqualTo("xxxxx@example.com")
}
}
参考(Javaの記事です)
Spring Bootで簡単なコマンドラインアプリケーションを作成してみる
https://reasonable-code.com/command-line-runner/
Spring Bootでコマンドラインアプリを作る時の注意点
https://qiita.com/tag1216/items/898348a7fc3465148bc8#comments
SpringBootでのJUnitでCommandLineRunnerが動くことの回避策
https://qiita.com/salkun/items/721125f0deec0a082504