【SpringBoot】怎样在SpringBoot程序启动后立即执行一些代码


SpringBoot成功启动后后会有Started MyApplication in 7.008 seconds (JVM running for 8.53) 这种类似的字样,

如果需要在此之后执行一些代码,可以这样做一个类:

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class ApplicationRunnerConfig implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("本条代码将在Started MyApplication之后执行。");
    }
}

完毕后,启动应用会发现控制台里有如下字样:

2022-05-06 22:54:33.406 - Tomcat started on port(s): 8080 (http) with context path '/dmo'
2022-05-06 22:54:33.435 - Started MyApplication in 7.008 seconds (JVM running for 8.53)
本条代码将在Started MyApplication之后执行。

这说明此类确如预期启动了。

参考资料:https://blog.csdn.net/mengyuanye/article/details/122146963

END

相关