After the SpringBoot project is started, there are five ways to execute the method:
1. Implement the CommandLineRunner interface
The method will be called and the service will be provided after the project is initialized.
@Component public class StartInit2 implements CommandLineRunner { @Override public void run(String... args) throws Exception { ("CommandLineRunner===================="); } }
2. Implement the ApplicationRunner interface
Same as CommandLineRunner. It's just that the transmission format is different. CommandLineRunner: No restrictions; ApplicationRunner: key-value
@Component public class StartInit3 implements ApplicationRunner { @Override public void run(ApplicationArguments args) { ("ApplicationRunner================="); } }
3. Implement the ApplicationListener interface
The method will be called to provide services only after the project is initialized. Pay attention to the listening events, usually ApplicationStartedEvent or ApplicationReadyEvent, and other events may not be injected into the bean.
@Component public class StartInit4 implements ApplicationListener<ApplicationStartedEvent> { @Override public void onApplicationEvent(ApplicationStartedEvent event) { ("ApplicationListener================ApplicationStartedEvent"); } }
- If the monitor is
ApplicationStartedEvent
Events, the ApplicationListener will be executed before CommandLineRunner and ApplicationRunner; - If the monitor is
ApplicationReadyEvent
Events, the ApplicationListener will be executed after CommandLineRunner and ApplicationRunner;
order:
The default isApplicationRunner
Execute first, if both parties specify@Order
Then follow@Order
The size order of the small ones are executed first.
principle:
- The run method of SpringApplication will execute the afterRefresh method.
- The afterRefresh method executes the callRunners method.
- callRunners method will call all methods that implement ApplicationRunner and CommonLineRunner interface callRunners method will call all methods that implement ApplicationRunner and CommonLineRunner interfaces callRunners method will call all methods that implement ApplicationRunner and CommonLineRunner interfaces
4. @PostConstruct annotation
This method is called during project initialization. If the business logic is time-consuming, it may cause the project to start failure.
@Component public class StartInit { @PostConstruct public void init() { ("@PostConstruct==============================="); } }
5. Implement the InitializingBean interface
This method is called when the project starts
@Component public class StartInit6 implements InitializingBean { @Override public void afterPropertiesSet() { ("InitializingBean===================="); } }
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.