Spring Boot – ApplicationRunner
What is use of Spring Boot ApplicationRunner Interaface?
Spring bootApplicationRunner
Interface is used to execute specific lines of code/task just before the Spring Boot Application starts-up.
ApplicationRunner
andCommandLineRunner
interfaces work in the same way and offer a singlerun
method, which is called just beforeSpringApplication.run(…)
completes.
How Spring boot ApplicationRunner interface Works?
We need to create spring bean using ApplicationRunner
interface and spring boot will automatically detect them. ApplicationRunner
Interface have run()
method that needs to be overridden in implementing class and make the class as bean by using spring stereotype such as @Component
.
The arguments which we pass to main() method while starting spring boot, can be accessed in the run() method of ApplicationRunner
. run()
method accepts Application Arguments
instead of array of String as an argument as in CommandLineRunner
.
We can create more than one bean of ApplicationRunner
implementing classes. To execute them in an order, we use spring @Order
annotation or Ordered interface.
Accessing Application Arguments
If you need to access the application arguments that were passed to SpringApplication.run(…)
, you can inject aorg.springframework.boot.ApplicationArguments
bean. The ApplicationArguments
interface provides access to both the raw String[]
arguments as well as parsed option
and non-option
arguments, as shown in the following example:
@Component public class ApplicationRunnerBean implements ApplicationRunner { private static Logger LOG = LoggerFactory.getLogger(ApplicationRunnerBean.class); @Override public void run(ApplicationArguments args) throws Exception { LOG.info("EXECUTING : Application Runner Bean"); System.out.println("Option Arguments are :"); Set<String> optionNames = args.getOptionNames(); for (String optionName : optionNames) { System.out.println(optionName + " : " + args.getOptionValues(optionName)); } System.out.println("Non Option Arguments are : "); List<String> nonOptionArgs = args.getNonOptionArgs(); for (String arg : nonOptionArgs) { System.out.println(arg); } System.out.println("Source args are:"); String[] sourceArgs = args.getSourceArgs(); for (String sourceArg : sourceArgs) { System.out.println(sourceArg); } } }
Let’s execute above bean passing argument to our project as below,
Arguments prefixed with — , for example
--Name=Talksinfo
is a valid option argument.If the argument value is not prefixed with
--
, it is a plain or Non option argument.
While executing the console gives us log as below,
EXECUTING : Application Runner Bean Option Arguments are : Purpose : [Learning] Name : [TalksInfo] Non Option Arguments are : Hello HAPPYLEARNING Source args are: Hello --Name=TalksInfo --Purpose=Learning HAPPYLEARNING
Conclusion
Hence we saw how to use spring boot ApplicationRunner interface and pass arguments and receive it based on options available.