官术网_书友最值得收藏!

How it works...

If we run our application again, by executing $ ./gradlew clean bootRun, we will get an output that is similar to the previous one. However, we will see our Hello message in the logs as well, which is as follows:

2017-12-16 21:57:51.048  INFO --- 
com.example.bookpub.StartupRunner : Hello

Even though the program will get terminated on execution, at least we made it do something!

Command-line runners are a useful functionality to execute the various types of code that only have to be run once, after startup. Some also use this as a place to start various executor threads, but Spring Boot provides a better solution for this task, which will be discussed at the end of this chapter. The command-line runner interface is used by Spring Boot to scan all of its implementations and invoke each instance's run method with the startup arguments. We can also use an @Order annotation or implement an Ordered interface so as to define the exact order in which we want Spring Boot to execute them. For example, Spring Batch relies on the runners to trigger the execution of the jobs.

As the command-line runners are instantiated and executed after the application has started, we can use the dependency injection to our advantage to wire in whatever dependencies we need, such as datasources, services, and other components. These can be utilized later while implementing run.

It is important to note that if any exception is thrown in the run(String... args) method, this will cause the context to close and an application to shut down. Wrapping the risky code blocks with try/catch is recommended to prevent this from happening.
主站蜘蛛池模板: 贡觉县| 汉川市| 四会市| 夏河县| 东至县| 临沧市| 巴林右旗| 平罗县| 社会| 万州区| 泰兴市| 滦南县| 封丘县| 新竹县| 绩溪县| 宜丰县| 年辖:市辖区| 福泉市| 西乡县| 射阳县| 栾川县| 新营市| 德州市| 六盘水市| 商水县| 九龙坡区| 武川县| 汝州市| 油尖旺区| 阳春市| 图木舒克市| 新安县| 洞头县| 淳安县| 拉萨市| 前郭尔| 云林县| 潢川县| 梓潼县| 浙江省| 斗六市|