2020-09-23 springboot启动后执行初始化的方式

springboot项目启动后进行初始化工作,如查询数据库,初始化容器数据

方式一

import org.springframework.boot.CommandLineRunner;

import org.springframework.stereotype.Component;



@Component

public class CommandLineRunnerImpl implements CommandLineRunner {

    @Override

    public void run(String... args) throws Exception {

        System.out.println("通过实现CommandLineRunner接口,在spring boot项目启动后打印参数");

        for (String arg : args) {

            System.out.print(arg + " ");

        }

        System.out.println();

    }

}

方式二: 

@Component
public class StartInit {
//
//    @Autowired   可以注入bean
//    ISysUserService userService;

    @PostConstruct
    public void init() throws InterruptedException {
        Thread.sleep(10*1000);//这里如果方法执行过长会导致项目一直无法提供服务
        System.out.println(123456);
    }
}

方式三(参考:ApplicationRunner用法_神明在左的博客-CSDN博客_applicationrunner):

@Component  //此类一定要交给spring管理
public class ConsumerRunner implements ApplicationRunner{
	@Override
	public void run(ApplicationArgumers args) throws Exception{
		//代码
		System.out.println("需要在springBoot项目启动时执行的代码---");
	}
}

可设置执行的先后顺序

@Component  //此类一定要交给spring管理
@Order(value=1) //首先执行
public class ConsumerRunnerA implements ApplicationRunner{
	@Override
	public void run(ApplicationArgumers args) throws Exception{
		//代码
		System.out.println("需要在springBoot项目启动时执行的代码1---");
	}
}


@Component  //此类一定要交给spring管理
@Order(value=2) //其次执行
public class ConsumerRunnerB implements ApplicationRunner{
	@Override
	public void run(ApplicationArgumers args) throws Exception{
		//代码
		System.out.println("需要在springBoot项目启动时执行的代码2---");
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值