package com.custom.webui.config; import com.custom.webui.config.props.StorageProperties; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** * 启动自检:把关键数据的**实际落盘位置**打进启动日志。 * *
为什么需要它:{@code webui.storage.location} 是相对路径, * 相对路径按「进程工作目录」解析,而工作目录随启动方式变化 —— * 在 IDE 里以 webui-springboot 为工作目录启动,和从项目根目录 * {@code java -jar} 启动,会指向两个不同的目录。 * *
这个差异不会在启动时报任何错,只会在用户真正上传或读取文件时才炸, * 而且表现为「知识库里的文件找不到」这种极易误判成数据丢失的现象。 * 把路径在启动时就打出来,问题一眼可见。 * *
这只是**可观测性**措施,不是校验门禁:目录不存在也不阻断启动 —— * 首次上传会自动创建,硬失败反而会把「只是想先起个服务看看」的人挡在门外。 */ @Slf4j @Component @RequiredArgsConstructor public class StartupDiagnostics { private final StorageProperties storageProperties; @EventListener(ApplicationReadyEvent.class) public void reportStorageLocations() { Path cwd = Paths.get("").toAbsolutePath().normalize(); Path uploadRoot = Paths.get(storageProperties.getLocation()).toAbsolutePath().normalize(); log.info("=".repeat(66)); log.info("存储位置自检(如需固定位置,请把 webui.storage.location 配成绝对路径)"); log.info(" 进程工作目录 : {}", cwd); log.info(" 配置值 : {}", storageProperties.getLocation()); log.info(" 实际上传目录 : {}", uploadRoot); log.info(" 目录状态 : {}", describe(uploadRoot)); log.info("=".repeat(66)); } private String describe(Path path) { if (Files.isDirectory(path)) { try (var stream = Files.walk(path, 4)) { long files = stream.filter(Files::isRegularFile).count(); return "已存在,含 " + files + " 个文件"; } catch (Exception e) { return "已存在,但统计文件数失败: " + e.getMessage(); } } if (Files.exists(path)) { return "存在但不是目录(配置有误)"; } return "尚不存在,首次上传时会自动创建"; } }