自学内容网 自学内容网

Spring Boot自定义配置项

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);
        }
    }

原文地址:https://blog.csdn.net/qq_59636442/article/details/142467315

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!