实现CommandLineRunner接口完成系统模板文件的初始化
背景:本文涉及的系统,业务文件全部存储于华为obs,系统用到的模板文件以及默认图标、轮播图等均存储到业务库obs,进入系统时下载展示文件。今天记录一下如何在项目部署启动的同时,把系统用到的一些模板文件(excel模板,pdf文件,系统图片)上传到系统obs文件存储系统,已达到模板文件初始化的目的。
文章目录
前言
Spring Boot中的CommandLineRunner接口允许你在Spring Boot应用程序启动后执行一些代码。通过实现CommandLineRunner接口,你可以编写自定义的CommandLineRunner实现类,以在应用程序启动时执行特定的操作。
一、初始化文件存放路径
在项目的根目录resources下,新建目录分别用于存放需要初始化的文件和图片,文件命名方式:32位uuid_中文名.文件后缀(后缀可以是png、docx、pdf、xlsx等)
二、实现方法
1.自定义InitFileData类实现CommandLineRunner
代码如下(示例):
/**
* 首次启动初始化默认图标文件
*/
@Component
@Order(1) // 初始化加载优先级,数字越小优先级越高
@Slf4j
public class InitFileData implements CommandLineRunner {
@Autowired
private IFileUploadService fileUploadService;
@Override
public void run(String... args) throws Exception {
log.info("开始文件初始化");
List<String> locations = new ArrayList<>();
locations.add("classpath:initialize/files/*");
locations.add("classpath:initialize/images/*");
//遍历读取项目包中的文件
locations.stream().forEach(location ->{
try {
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resourcePatternResolver.getResources(location);
for ( Resource resource : resources ) {
//获取文件,在打成jar包后,通过url来获取文件,则路径是正确的
File file = new File(resource.getURL().getFile());
String item = file.