使用CommandLineRunner遇到的坑

使用Spring Boot 的CommandLineRunner遇到的坑

启动时失败

原因

CommandLineRunner的run方法是单线程执行的,当存在时间过长或多个线程执行时,有可能遇到阻塞会停止

解决办法
开启新的线程进行执行
@Component
public class ScheduleJobInitListener implements CommandLineRunner {

    @Autowired
    TaskService scheduleJobService;

    @Override
    public void run(String... arg0) throws Exception {
        new Thread() {
            public void run() {
                try {
                    scheduleJobService.initSchedule();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}

执行成功,打包失败,显示JdbcSQLException: not found table ‘XXX’

经过网上的搜查,显示提示这个错误的原因是字段写错,或大小写异常。但与碰到的问题不一样。我进行了如下筛查:

  1. 先行确认代码是否存在编写错误;
  2. 大小写问题;
  3. 将测试类打包注释掉,通过。
原因

commandLineRunner会在测试时自行加载。导致测试失败。启动新的线程也会报错。但加上睡眠时间就会发现正常了。故测试时CommandLineRunner先于表加载

@Override
    public void run(String... arg0) throws Exception {
        new Thread() {
            public void run() {
                try {
                    sleep(1000);
                    scheduleJobService.initSchedule();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
解决办法

经过网上的查找找到一种方式:在引CommandLineRunner的类上加注解@Profile("!test")进行排除测试类。具体可以在测试的配置文件中加spring.profiles.active=test

@Component
@Profile("!test")
public class ScheduleJobInitListener implements CommandLineRunner {

    @Autowired
    TaskService scheduleJobService;

    @Override
    public void run(String... arg0) throws Exception {
        new Thread() {
            public void run() {
                try {
                    scheduleJobService.initSchedule();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值