SpringBoot自定义配置项过程
作者:CY耶
在SpringBoot项目中,通过在application.properties文件中添加配置项,然后使用@ConfigurationProperties注解将这些配置项与实体Bean进行绑定,可以实现配置项与实体类字段的自动关联,进而方便地读取配置文件中的数据,这种方法不仅简化了配置管理
Spring Boot自定义配置项
配置文件
在application.properties文件添加需要的配置
比如:
file.path=D:\\flies\\springboot\\
@ConfigurationProperties 注解
使用注解@ConfigurationProperties将配置项和实体Bean关联起来
实现配置项和实体类字段的关联,读取配置文件数据
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "file")
public class FileConfig {
private String path;
}使用
获取配置信息
FileConfig fileConfig = new FileConfig(); // 文件保存目录 String filePath = fileConfig.getPath();
@PostMapping("/upload/")
@ResponseBody
public Response upload(MultipartFile file) {
// 验证是否有文件
if(file == null || file.isEmpty()){
return Response.newFail("Upload failed, please select file",400);
}
FileConfig fileConfig = new FileConfig();
// 文件保存目录
String filePath = fileConfig.getPath();
// 验证文件夹
File folder = new File(filePath);
if (!folder.exists()) {
folder.mkdirs();
}
// 文件名
String fileName = UUID.randomUUID() + file.getOriginalFilename();
filePath = filePath + fileName;
File saveFile = new File(filePath);
try {
file.transferTo(saveFile);
return Response.newSuccess("Upload successful");
} catch (IOException e) {
e.printStackTrace();
return Response.newFail("Upload failed",50001);
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
