Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Spring Boot 2.0 Cookbook

You're reading from   Spring Boot 2.0 Cookbook Configure, test, extend, deploy, and monitor your Spring Boot application both outside and inside the cloud

Arrow left icon
Product type Paperback
Published in Feb 2018
Publisher
ISBN-13 9781787129825
Length 286 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Alex Antonov Alex Antonov
Author Profile Icon Alex Antonov
Alex Antonov
Arrow right icon
View More author details
Toc

Table of Contents (11) Chapters Close

Preface 1. Getting Started with Spring Boot 2. Configuring Web Applications FREE CHAPTER 3. Web Framework Behavior Tuning 4. Writing Custom Spring Boot Starters 5. Application Testing 6. Application Packaging and Deployment 7. Health Monitoring and Data Visualization 8. Spring Boot DevTools 9. Spring Cloud 10. Other Books You May Enjoy

Using the command-line runners

With our basic application skeleton ready, let's add some meat to the bones by making our application do something.

Let's start by first creating a class named StartupRunner. This will implement the CommandLineRunner interface, which basically provides just one method: public void run(String... args) --that will get called by Spring Boot only once after the application has started.

How to do it...

  1. Create the file named StartupRunner.java under the src/main/java/com/example/bookpub/ directory from the root of our project with the following content:
        package com.example.bookpub; 

import com.example.bookpub.repository.BookRepository; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Scheduled;

public class StartupRunner implements CommandLineRunner { protected final Log logger = LogFactory.getLog(getClass()); @Override public void run(String... args) throws Exception { logger.info("Hello"); }
}
  1. After we have defined the class, let's proceed by defining it as @Bean in the BookPubApplication.java application configuration, which is located in the same folder as our newly created StartupRunner.java file as follows:
@Bean 
public StartupRunner schedulerRunner() { 
    return new StartupRunner(); 
} 

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.
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime