在Spring Boot应用中,如果你想在应用启动完成后执行一些特定的操作(例如缓存预热),可以实现CommandLineRunner
或ApplicationRunner
接口。这两个接口都提供了一个run方法,在Spring Boot应用上下文初始化完成后会被自动调用。
CommandLineRunner
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class StartupRunner implements CommandLineRunner {
@Autowired
private YourService yourService; // 你的服务类
@Override
public void run(String... args) throws Exception {
// 在这里编写启动后需要执行的操作
yourService.cacheWarmUp(); // 假设这是一个用于预热缓存的方法
System.out.println("Application started successfully...");
}
}
ApplicationRunner
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.ster