CommandLineRunner
CommandLineRunner的使用 - 盐小果 - 博客园 (cnblogs.com)
问题:在项目启动时,我们需要加载或者预先完成某些动作,该怎么办呢?
解决办法:在springBoot中是实现CommandLineRunner接口类
CommandLineRunner翻译过来就是“命令行运行者”,很形象😏
@SpringBootApplication public class Demo03Application { public static void main(String[] args) { System.out.println("step 1: The Service will start"); SpringApplication.run(Demo03Application.class, args); System.out.println("step 5: The Service has started"); } } @Component @Order(1) class Runner1 implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("step 3: The Runner1 run..."); } } @Component @Order(2) class Runner2 implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("step 4: The Runner1 run..."); } }
由以上代码可以发现:在SpringApplication.run运行完之后才会运行自己创建的实现类,并且自己的实现类通过@Order()
注解控制顺序,数字越小越靠前。
思考一下为什么要加@Component注解呢?
(1)、加入@Component注解后,就可以将对象交给spring管理。
(2)、当Spring 容器初始化完成后, Spring会遍历所有实现CommandLineRunner接口的类, 并运行其run() 方法.
2. @SpringBootApplication实现
@SpringBootApplication public class Demo03Application implements CommandLineRunner{ public static void main(String[] args) { System.out.println("step 1: The Service will start"); SpringApplication.run(Demo03Application.class, args); System.out.println("step 5: The Service has started"); } @Override public void run(String... args) throws Exception { System.out.println("app start"); } }
3. @Bean实现
@SpringBootApplication public class SpringBootWebApplication extends SpringBootServletInitializer { public static void main(String[] args) throws Exception { SpringApplication.run(SpringBootWebApplication.class, args); } @Bean public ApplicationStartupRunner schedulerRunner() { return new ApplicationStartupRunner(); } } public class ApplicationStartupRunner implements CommandLineRunner { protected final Log logger = LogFactory.getLog(getClass()); @Override public void run(String... args) throws Exception { logger.info("Application Started !!"); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律