ApplicationListenerf4b06c38ff2750052547656f66f34e34 Not recommended
ApplicationListener Recommended
CommandLineRunner Recommended
Implement the ApplicationListener interface and implement the onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) method
@Service public class SearchReceive implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { if (contextRefreshedEvent.getApplicationContext().getParent() == null) {//保证只执行一次 //需要执行的方法 } } }
ApplicationListener and CommandLineRunner interfaces are provided by springBoot to execute specified methods after the spring container is loaded. The main difference between the two interfaces is the input parameters.
Implement ApplicationRunner interface
@Component @Order(value = 1) public class AfterRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("执行方法"); } }
Implement CommandLineRunner interface
@Component @Order(value = 2) public class CommandLineRunnerImpl implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("执行方法"); } }
Note: If you implement both ApplicationListener and CommandLineRunner interfaces at the same time , the methods of the ApplicationRunner interface are executed first, and then the CommandLineRunner;
@Slf4j @Component public class RunnerTest implements ApplicationRunner, CommandLineRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("服务启动RunnerTest ApplicationRunner执行启动加载任务..."); } @Override public void run(String... args) throws Exception { System.out.println("服务启动RunnerTest CommandLineRunner 执行启动加载任务..."); } } }
When both the ApplicationRunner and CommondLineRunner interfaces are implemented in the project, you can use the Order annotation or implement the Ordered interface. Specify the execution order, the smaller the value, the first to execute.
The run method of SpringApplication will execute the afterRefresh method.
The afterRefresh method will execute the callRunners method.
The callRunners method will call all methods that implement the ApplicationRunner and CommondLineRunner interfaces.
The above is the detailed content of What are the execution methods after the springboot project is started?. For more information, please follow other related articles on the PHP Chinese website!