Actual application scenarios: After the Springboot project is successfully started, a piece of code is executed, such as initialization operations of system constants, configurations, code sets, etc. When executing multiple methods, the Order of execution is controlled using the Order annotation or the Order interface.

Springboot gives us two ways to do this

The first implements the ApplicationRunner interface

package org.mundo.demo.core; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component @Order(2) public class ApplicationRunnerImpl implements ApplicationRunner { @Override public void Run (ApplicationArguments args) throws Exception {system.out.println (" Execute code after the Spring Boot project starts by implementing the ApplicationRunner interface..." ); }}Copy the code

The second implements the CommandLineRunner interface

package org.mundo.demo.core; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component @Order(1) public class CommandLineRunnerImpl implements CommandLineRunner { @Override public void run(String... Args) throws Exception {system.out.println (" Executes code after the Spring Boot project is started by implementing the CommandLineRunner interface..." ); }}Copy the code

Contrast:

Similarities: Both methods provide the purpose of executing certain methods immediately upon project startup, and both start executing after The SpringApplication execution.

Differences: The CommandLineRunner interface can be used to receive command-line arguments to an array of strings, whereas ApplicationRunner uses ApplicationArguments to receive arguments

Note:

The @ORDER or Ordered interface is used to define the priority of the execution Order of beans in the Spring IOC container, not the load Order of beans. The loading Order of beans is not affected by the @Order or Ordered interface;

2. When both ApplicationRunner and CommondLineRunner interfaces are implemented in a project, the Order annotation or Ordered interface can be used to specify the execution Order. The smaller the value, the higher the execution Order

3, annotation has a parameter of type int, can not pass, default is the lowest priority;