springboot:commandlinerunner

CommandLineRunner

In Spring, CommandLineRunner run right after the application is initialized. It will run only one time, and it is good for initialize values for your application. We can implement it in the root application class, or creating new class with @Component on the top of it. We can have multiple CommandLineRunners, and we can use @Order(1), @Order(2), … to control the running order.

To implement CommandLineRunner, we need to overrider the following function, and the spring will call it automatically.

@Override
public void run(String... args) throws Exception {
   ...
}

In this example, we create two users in our data source for our application for testing in the CommandLineRunner.

@SpringBootApplication
public class MyApplication implements CommandLineRunner {
    @Autowired
    private ApplicationUserRepository applicationUserRepository;

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

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void run(String... args) throws Exception {
        applicationUserRepository.save(new ApplicationUser("user", bCryptPasswordEncoder().encode("password"), "USER"));
        applicationUserRepository.save(new ApplicationUser("admin", bCryptPasswordEncoder().encode("password"), "ADMIN"));
    }

}

In order to let spring create your bean, you need to add @Component at the top of your class. Without it, you class will not be create, and the CommandLineRunner will not be called.

Here we have two classes. In order to control the running order, we use @Order(1), @Order(2). Logically, we can have as many CommandLineRunner as you want.

@Component
@Order(1)
public class TestCmdRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("TESTING 1 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    }
}
@Component
@Order(2)
public class TestCmdRunner2 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("TESTING 2 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    }
}
  • springboot/commandlinerunner.txt
  • Last modified: 2020/06/11 11:14
  • by chongtin