Spring boot 之CommandLineRunner 系统启动时增加一些随带的信息一起加载数据

实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求。 
为了解决这样的问题,Spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来实现。

很简单,只需要一个类就可以,无需其他配置。 
创建实现接口 CommandLineRunner 的类

Spring Boot应用程序在启动后,会遍历CommandLineRunner接口的实例并运行它们的run方法。

@Order 注解的执行优先级是按value值从小到大顺序执行run() 

多个类实现CommandLineRunner接口run()方法处理不同的业务,再按order顺序执行。这样可以把一些数据在系统启动的时候就进行初始化加载 比如数据字典,或者一些数据库表数据等

package com.mwkj.platform.manage.application;

import com.mwkj.common.constant.CommonConstant;
import com.mwkj.common.resp.ResponseMessage;
import com.mwkj.platform.rpc.pojo.dict.entity.SysDictEntity;
import com.mwkj.platform.rpc.service.dict.SysDictServiceImpl;
import com.mwkj.platform.rpc.xmlentity.SysConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

/**
* Created by .
* 系统参数初始化
*/
@Component
@Order(2) //跟据这个order值从小到大的顺序来执行对应实现了CommandLineRunner 接口的类下面的run()方法
public class PlatformManageInit implements CommandLineRunner {

@Autowired
private SysDictServiceImpl sysDictService;

@Override
public void run(String... args) throws Exception {
System.out.print("---------------字典数据初始化-START----------------\n");
SysDictEntity entity = new SysDictEntity();
entity.setStatus(CommonConstant.STATUS_ENABLE);
List sysDicts = sysDictService.getDictsBycodeType(entity);
SysConstants.putDict(sysDicts);
System.out.print("---------------字典数据初始化-END----------------\n");
}
}

 

转载于:https://www.cnblogs.com/leeIndex/p/8891487.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值