Kotlin command line runner

Core Features

This section dives into the details of Spring Boot. Here you can learn about the key features that you may want to use and customize. If you have not already done so, you might want to read the «Getting Started» and «Developing with Spring Boot» sections, so that you have a good grounding of the basics.

1. SpringApplication

The SpringApplication class provides a convenient way to bootstrap a Spring application that is started from a main() method. In many situations, you can delegate to the static SpringApplication.run method, as shown in the following example:

import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyApplication < public static void main(String[] args) < SpringApplication.run(MyApplication.class, args); >> 
import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class MyApplication fun main(args: Array) < runApplication(*args) > 

When your application starts, you should see something similar to the following output:

. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v3.1.2) 2023-07-20T10:14:22.704Z INFO 35977 --- [ main] o.s.b.d.f.s.MyApplication : Starting MyApplication using Java 17.0.7 with PID 35977 (/opt/apps/myapp.jar started by myuser in /opt/apps/) 2023-07-20T10:14:22.710Z INFO 35977 --- [ main] o.s.b.d.f.s.MyApplication : No active profile set, falling back to 1 default profile: "default" 2023-07-20T10:14:23.948Z INFO 35977 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2023-07-20T10:14:23.961Z INFO 35977 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2023-07-20T10:14:23.961Z INFO 35977 --- [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.11] 2023-07-20T10:14:24.120Z INFO 35977 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2023-07-20T10:14:24.124Z INFO 35977 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1336 ms 2023-07-20T10:14:24.656Z INFO 35977 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2023-07-20T10:14:24.671Z INFO 35977 --- [ main] o.s.b.d.f.s.MyApplication : Started MyApplication in 2.45 seconds (process running for 2.852)

By default, INFO logging messages are shown, including some relevant startup details, such as the user that launched the application. If you need a log level other than INFO , you can set it, as described in Log Levels. The application version is determined using the implementation version from the main application class’s package. Startup information logging can be turned off by setting spring.main.log-startup-info to false . This will also turn off logging of the application’s active profiles.

Читайте также:  Чем просмотреть результат html
To add additional logging during startup, you can override logStartupInfo(boolean) in a subclass of SpringApplication .

1.1. Startup Failure

If your application fails to start, registered FailureAnalyzers get a chance to provide a dedicated error message and a concrete action to fix the problem. For instance, if you start a web application on port 8080 and that port is already in use, you should see something similar to the following message:

*************************** APPLICATION FAILED TO START *************************** Description: Embedded servlet container failed to start. Port 8080 was already in use. Action: Identify and stop the process that is listening on port 8080 or configure this application to listen on another port.

If no failure analyzers are able to handle the exception, you can still display the full conditions report to better understand what went wrong. To do so, you need to enable the debug property or enable DEBUG logging for org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener .

For instance, if you are running your application by using java -jar , you can enable the debug property as follows:

$ java -jar myproject-0.0.1-SNAPSHOT.jar --debug

1.2. Lazy Initialization

SpringApplication allows an application to be initialized lazily. When lazy initialization is enabled, beans are created as they are needed rather than during application startup. As a result, enabling lazy initialization can reduce the time that it takes your application to start. In a web application, enabling lazy initialization will result in many web-related beans not being initialized until an HTTP request is received.

A downside of lazy initialization is that it can delay the discovery of a problem with the application. If a misconfigured bean is initialized lazily, a failure will no longer occur during startup and the problem will only become apparent when the bean is initialized. Care must also be taken to ensure that the JVM has sufficient memory to accommodate all of the application’s beans and not just those that are initialized during startup. For these reasons, lazy initialization is not enabled by default and it is recommended that fine-tuning of the JVM’s heap size is done before enabling lazy initialization.

Lazy initialization can be enabled programmatically using the lazyInitialization method on SpringApplicationBuilder or the setLazyInitialization method on SpringApplication . Alternatively, it can be enabled using the spring.main.lazy-initialization property as shown in the following example:

spring.main.lazy-initialization=true

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

This is the source code for the a sample CommandLineRunner Spring Boot application developed with Kotlin.

flanfl/kotlin-commandlinerunner-spring-boot

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

CommandLineRunner Spring Boot Kotlin sample project

This is the source code for the a sample CommandLineRunner Spring Boot application developed with Kotlin.

You can launch the application with by running:

The project can be build with

And it is possible to run the jar file located in the build/lib folder

This project uses kotlin-spring plugin to avoid requiring open modifier on proxified classes and methods, see this blog post for more details.

Make sure you have at least IntelliJ IDEA 2016.3 and Kotlin plugin 1.0.6 since kotlin-spring require this version.

This project uses a Kotlin based Gradle configuration, but build.gradle.kts auto-complete is currently not available since Kotlin 1.1-M04 IDEA plugin needed for that does not allow to use kotlin-spring compiler in a reliable way.

This project is based on sdeleuze own sample projet.

About

This is the source code for the a sample CommandLineRunner Spring Boot application developed with Kotlin.

Источник

Kotlin spring commandlinerunner

Kotlin spring commandlinerunner

To learn about Kotlin Spring dependency injection, refer to this article.

2. Kotlin spring commandlinerunner

If you need to run some specific code once the SpringApplication has started, you can implement the CommandLineRunner interface. It is a functional interface, meaning it contains exactly one abstract method run .

This interface is well suited for tasks that should run after application startup but before it starts accepting traffic.

@FunctionalInterface public interface CommandLineRunner

Both CommandLineRunner and ApplicationRunner interfaces work in the same way and offer a single run method, which is called just before SpringApplication.run(…​) completes.

The CommandLineRunner interfaces provide access to application arguments as a string array.

@Component class CommandExample : CommandLineRunner < override fun run(vararg args: String?) < println("Command line runner 1 run method") >>

If several CommandLineRunner beans are defined that must be called in a specific order, you can additionally implement the org.springframework.core.Ordered interface or use the org.springframework.core.annotation.Order annotation.

Since Spring 4.0, @Order supports the ordering of injected components to a collection. As a result, Spring will inject the auto-wired beans of the same type based on their order value.

For example, the following components are sorted using the @Order annotation. The component CommandExample has order 2 whereas CommandExample2 has order 1. Therefore, Spring injects the commandExample2 bean before the CommandExample bean.

import org.springframework.core.annotation.Order import org.springframework.stereotype.Component @Component @Order(2) class CommandExample : CommandLineRunner < override fun run(vararg args: String?) < println("Command line runner 1 run method") >> @Component @Order(1) class CommandExample2 : CommandLineRunner < override fun run(vararg args: String?) < println("Command line runner 2 run method") >>

If you execute the preceding code, the following results would appear in the console. As you can see, the run method of CommandExample2 executes before the CommandExample .

Command line runner 2 run method Command line runner 1 run method

2.1. Non web application with Spring CommandLineRunner

Not all Spring applications have to be web applications (or web services). To create a non-web application, implement CommandLineRunner and override the run method.

For example, the following code contains the main method as a top-level method and also implements the CommandLineRunner interface.

@SpringBootApplication open class DependencyInjectionApplication : CommandLineRunner < override fun run(vararg args: String?) < println("Non web app") // your code >> fun main(args: Array) < runApplication(*args) >

For these non-web applications, you can implement your business logic as a CommandLineRunner and drop it into the context as a @Bean definition.

3. Conclusion

To sum up, we have learned the Kotlin Spring CommandLineRunner with example. The above code samples are available in our GitHub repository.

Источник

Оцените статью