Java程序初始化启动自动执行的三种方法

目录

@PostConstruct注解

CommandLineRunner接口

ApplicationRunner 接口

@Order注解设置启动顺序


分享一下自己用过的java程序初始化启动自动执行的三种方法

@PostConstruct注解

将此注解加在要执行的方法上,则程序初始化启动的时候,会执行此方法,一般用来初始化必要的程序初始信息

注意:加了postconstruct注解的方法,如果执行失败,整个程序会无法正常启动!这个方法执行不完,整个程序也启动不了!!!

详情请看我的错误总结  开发错误总结---@PostConstruct注解导致的程序无法启动(@PostConstruct的执行)_是菜菜的小严惜哎的博客-CSDN博客

开始试验:

启动类

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class,args);
    }
}

测试类

@Service
@Slf4j
public class PostConstructTest {

    @PostConstruct
    public void testPostConstruct () {
      log.info("程序初始化执行");
    }

}

启动看效果

CommandLineRunner接口

实现 CommandLineRunner接口

@Slf4j
@Component
public class InitCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        log.info("实现CommandLineRunner接口的程序初始化");
    }
}

启动看效果

ApplicationRunner 接口

实现 ApplicationRunner 接口

@Component
@Slf4j
public class InitApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("实现ApplicationRunner接口程序初始化");
    }
}

启动看效果

@Order注解设置启动顺序

我们给前两个实现ApplicationRunner 接口和CommandLineRunner 接口的启动类设置启动顺序,为了让效果明显一点,我们让程序执行完第一个之后睡眠一下

@Slf4j
@Component
@Order(value = 1)
public class InitCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        log.info("实现CommandLineRunner接口的程序初始化");
        Thread.sleep(2000);
    }
}
@Component
@Slf4j
@Order(value = 2)
public class InitApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("实现ApplicationRunner接口程序初始化");
    }
}

执行一下来看效果

  • 8
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值