In Spring boot projects, CommandLineRunner
interface is used to run a code block only once in application’s lifetime – after application is initialized.
CommandLineRunner can be used in two ways:
Using CommandLineRunner as @Component
ApplicationStartupRunner
class implementsCommandLineRunner
interface.import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class ApplicationStartupRunner implements CommandLineRunner { protected final Log logger = LogFactory.getLog(getClass()); @Override public void run(String... args) throws Exception { logger.info("ApplicationStartupRunner run method Started !!"); } }
Implement CommandLineRunner in @SpringBootApplication
CommandLineRunner
interface is implemented onApplication
class, so override therun()
here itself.import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application implements CommandLineRunner { protected final Log logger = LogFactory.getLog(getClass()); public static void main( String[] args ) { SpringApplication.run(Application.class, args); } @Override public void run(String... args) throws Exception { logger.info("ApplicationStartupRunner run method Started !!"); } }
Ask Questions & Share Feedback