Junior — Middle
How to implement the launch of a specific business operation during application initialization in Spring Framework?
sobes.tech AI
Answer from AI
In the Spring Framework, to run a specific business operation during application startup, you can use the CommandLineRunner or ApplicationRunner interfaces. These interfaces allow you to execute code immediately after the Spring context has started.
Example using CommandLineRunner:
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class StartupBusinessOperation implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// Your business logic that should execute at application startup
System.out.println("Executing business operation during application initialization");
// for example, loading data, initializing cache, etc.
}
}
This component will automatically execute after the Spring Boot application starts. If using a traditional Spring setup without Boot, you can use InitializingBean or the @PostConstruct annotation to run code after bean initialization.