Introduction
In Spring Boot development, we often need to execute initialization tasks (such as loading configuration, warming up cache, and starting timing tasks) immediately after the application is started. This article will deeply analyze 5 mainstream implementation solutions, including complete code examples, execution order control techniques and pit avoidance guides!
1. Why do you need to automatically execute after startup?
Typical usage scenarios
Scene Type | Specific cases | Technical value |
---|---|---|
Data Initialization | Load dictionary data into memory | Improve interface response speed |
Timing task starts | Start distributed task scheduling | Make sure the task is executed after service is ready |
Resource preload | Warm up Redis cache | Avoid performance fluctuations caused by cold start |
Parameter verification | Check whether the necessary configuration items exist | Enhance system robustness |
Third-party service registration | Register an instance with the Service Registration Center | Ensure microservice availability |
2. Complete analysis of six major implementation plans
Solution 1: @PostConstruct (simple initialization)
@Service public class CacheInitializer { @PostConstruct public void init() { // Execute after bean initialization is completed loadAllConfigToCache(); ("Dictionary data loading is completed"); } }
Features:
- Execution time: Execute immediately after the dependency injection is completed
- Applicable scenario: Simple initialization of single beans
- Note: Cross-bean dependencies cannot be handled
Solution 2: ApplicationRunner (parameter resolution enhancement)
java @Component @Order(1) // Control the execution orderpublic class StartupRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) { // parse command line parameters boolean force = ("force"); String configFile = ("config").get(0); // Execute initialization logic ("Start with parameters:force="+force+", configFile="+configFile); } }
Advantages:
- Support command line parameter analysis
- Natural support @Order sort
Solution 3: ApplicationListener
@Component public class ApplicationReadyListener { @EventListener() public void onApplicationReady() { // Make sure all beans are initialized ("All components are ready, final initialization is performed"); } }
Special Values:
- Can listen to multiple application events (such as ApplicationStartingEvent)
- Suitable for scenarios where delayed execution is required
Solution 4: CommandLineRunner (basic parameter processing)
@Component public class ConfigLoader implements CommandLineRunner { @Override public void run(String... args) { // Process original command line parameters ("Original Parameters:"+(args)); } }
Applicable scenarios: Scenarios where string parameters are only required
Solution 5: Custom listener (complex process control)
@Component public class StartupListener implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (().getParent() == null) { // Execute only when root context is initialized ("Root context initialization is completed"); } } }
Advanced usage:
- Prevent multiple triggers (judgmented by context)
- Combined with @Async to achieve asynchronous initialization
Scheme 6: @Scheduled timed start (delayed execution)
@Component @EnableScheduling public class DelayedInitializer { @Scheduled(fixedDelay = 5000) // Execute after 5 seconds of the first delay public void delayedInit() { ("Delayed initialization task execution"); } }
Special scenarios: Initialization tasks that need to be delayed execution
3. Solution comparison decision matrix
plan | Execution timing | Parameter support | Execution order | Applicable complexity |
---|---|---|---|---|
@PostConstruct | Bean | After initialization | none | none |
ApplicationRunner | Application startup is completed | Analyze parameters | support | ★★★☆☆ |
ApplicationListener | Application event triggered | none | Need to be manually | ★★★★☆ |
@Scheduled | Timing trigger | none | none | ★★☆☆☆ |
4. Complete implementation process
Step 1: Create an initialization service
@Service public class StartupService { public void initConfig() { // Load configuration logic } public void warmUpCache() { // Cache warm-up logic } }
Step 2: Select the execution plan (taking ApplicationRunner as an example)
@Component @Order(1) public class StartupRunner implements ApplicationRunner { private final StartupService startupService; public StartupRunner(StartupService startupService) { = startupService; } @Override public void run(ApplicationArguments args) { (); (); } }
Step 3: Configure the execution order (when multiple initialization tasks)
@Component @Order(2) public class SecondaryInitializer implements CommandLineRunner { // Secondary initialization task}
5. Pit avoidance guide and best practices
1. Circular Dependency Trap
// Error example: A depends on B, B depends on A@Service public class AService { private final BService bService; public AService(BService bService) { = bService; } @PostConstruct public void init() { (); // Trigger cyclic dependency } }
Solution: Lazy loading with @Lazy
2. Execute configuration asynchronously
@EnableAsync @Configuration public class AsyncConfig { @Bean public Executor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); (5); (100); return executor; } } // Add asynchronous execution on the method@Async public void asyncInit() { // Asynchronous initialization logic}
3. Execution sequence control
@Component @Order(1) // The smaller the number, the higher the prioritypublic class FirstInitializer implements ApplicationRunner {} @Component @Order(2) public class SecondInitializer implements ApplicationRunner {}
VI. Production environment verification plan
1. Unit Testing
@SpringBootTest class StartupTest { @Autowired private StartupService startupService; @Test void testInitSequence() { // Verify the initialization order verifyOrder(startupService::initConfig, startupService::warmUpCache); } }
2. Log monitoring
2025-04-09 09:00:00.000 INFO 12345 --- [ main] : === Application startup initialization start ===
2025-04-09 09:00:00.100 INFO 12345 --- [ main] : Dictionary data is loaded (time taken 85ms)
2025-04-09 09:00:00.200 INFO 12345 --- [ main] : === All initialization tasks are completed ===
7. Extended scenario solution
1. Distributed lock control (anti-repeated execution)
@PostConstruct public void distributedInit() { RLock lock = ("startup:init"); if ((0, 60, )) { try { // Execute initialization } finally { (); } } }
2. Health examination linkage
@EventListener() public void healthCheck() { HealthIndicator indicator = (); if (!().getStatus().equals()) { throw new RuntimeException("Dependency service not ready"); } }
8. Summary and selection suggestions
Demand scenarios | Recommended plan |
---|---|
Simple initialization | @PostConstruct |
Requires parameter processing | ApplicationRunner |
Need to monitor application status | ApplicationListener |
Delayed execution | @Scheduled |
Complex initialization process | Custom listener + asynchronous execution |
The above is the detailed content of five methods to automatically execute initialization tasks after SpringBoot is started. For more information about initialization after SpringBoot is started, please pay attention to my other related articles!