Codersee
Kotlin on the backend
Codersee
Kotlin on the backend
In this, step-by-step article, I will show you how to create a Spring Boot console app with Kotlin from scratch.
Hello! In this, short step-by-step guide, I will show you how to create a Spring Boot console app with Kotlin from scratch.
In this article, we will learn:
As the first step, let’s take a minute to understand what exactly CommandLineRunner is. As the documentation states:
Interface used to indicate that a bean should run when it is contained within a SpringApplication.
In simple terms, the CommanLineRunner is an interface, which contains one method- void run(String... args) throws Exception
, which we can implement and which will be invoked automatically, without us having to do it manually.
Moreover, we can implement it multiple times and control the order of invocation using the @Order annotation or the Ordered interface.
With that being said, let’s generate a new Spring Boot Kotlin application. To do so, let’s navigate to the Spring Initializr page and specify the following settings:
Basically, I would just like to emphasize that we don’t need any additional dependencies and the rest is totally up to you (and that I’m using the particular versions in case anything is deprecated in the future).
And once you pick your desired settings, please hit the Generate button and import the project to your IDE.
Finally, let’s open up our IDE and implement two classes called WillBeInvokedFirst and WillBeInvokedSecond:
@Component @Order(1) class WillBeInvokedFirst : CommandLineRunner { override fun run(vararg args: String) { print("Hello, ") } } @Component @Order(2) class WillBeInvokedSecond : CommandLineRunner { override fun run(vararg args: String) { println("World!") } }
As we can see, we have to do only three things to implement a command-line application:
Besides, no other changes are required. Nevertheless, please keep in mind that by default, the CommandlineApplication.kt file was added when creating a project:
@SpringBootApplication class CommandlineApplication fun main(args: Array<String>) { runApplication<CommandlineApplication>(*args) }
Finally, if we run the application we should see the following output:
Hello, World!
And that would be all for this short article on how to create a Spring Boot console app with Kotlin. If you’d like to clone the project, then you can find it in this GitHub repository.
Let me know in the comments section if you enjoy such short articles solving particular problems. Of course as an addition to standard, long tutorials.
Finally, if you enjoyed this one, then you might be interested in other Spring Boot articles I created so far.