Monday, February 3, 2020

How to Implement ApplicationRunner & ApplicationArguments in Spring Boot


In Spring Boot doc ApplicationArguments is autowired in a bean. Here is a more hands on example where it's used in a Main method.

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyApplication implements ApplicationRunner {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args).stop();
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        boolean debug = args.containsOption("debug");
        List<String> logFile = args.getOptionValues("logfile");
        List<String> nonOptionArgs = args.getNonOptionArgs();
        
        System.out.println("Debug : " + debug);
        System.out.println("Log File : " + logFile.get(0));
        System.out.println("Non Option Args : " + nonOptionArgs);
    }
}
Run on Command Line:
java -jar MyApp.jar --debug=true --logfile="C:/Logs/my-app.log" MyArgs2 "My Args3" "My @r9$4"
Output:
> Debug : true
> Log File : C:/Logs/my-app.log
> Non Option Args : [MyArgs2, My Args3, My @r9$4]

Reference:
Previous Post
Next Post

0 komentar: