Springboot2.x初始化 项目数据

Springboot2.x 初始化项目数据

1.初始化类
  • CommandLineRunner 接口的 Component 会在所有 Spring Beans 都初始化之后,SpringApplication.run() 之前执行,非常适合在应用程序启动之初进行一些数据初始化的工作
@Component
public class MyRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("在SpringApplication.run() 之前执行");
    }
}
2.在启动类上添加验证启动顺序
  • 在main方法里操作(不建议)
@SpringBootApplication
public class SpringApplication {

    public static void main(String[] args) {
        System.out.println("执行run之前");
        SpringApplication.run(SpringApplication.class, args);
        System.out.println("执行run之后");
    }
}
3.使用注解 @PostConstruct 和 @PreDestroy
  • @PostConstruct修饰的方法会在服务器加载Servle的时候运行,并且只会被服务器执行一次。
  • PostConstruct在构造函数之后执行,init()方法之前执行。
  • PreDestroy()方法在destroy()方法执行执行之后执行
 /**
     * @ PostConstruct修饰的方法会在服务器加载Servle的时候运行,
     * 并且只会被服务器执行一次。
     * PostConstruct在构造函数之后执行,init()方法之前执行。
     */
    @PostConstruct
    public void initializeUpdateExchangeRate() {
        updateExchangeRate();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值