首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Spring Boot自定义配置项

Spring Boot自定义配置项

作者头像
超级小的大杯柠檬水
发布2024-11-21 12:41:47
发布2024-11-21 12:41:47
19100
代码可运行
举报
文章被收录于专栏:CYCY
运行总次数:0
代码可运行

Spring Boot自定义配置项

配置文件

application.properties文件添加需要的配置 比如:

代码语言:javascript
代码运行次数:0
运行
复制
file.path=D:\\flies\\springboot\\

@ConfigurationProperties 注解

使用注解@ConfigurationProperties将配置项和实体Bean关联起来,实现配置项和实体类字段的关联,读取配置文件数据。

代码语言:javascript
代码运行次数:0
运行
复制
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;
}

使用

获取配置信息

代码语言:javascript
代码运行次数:0
运行
复制
FileConfig fileConfig = new FileConfig();
// 文件保存目录
String filePath = fileConfig.getPath();
代码语言:javascript
代码运行次数:0
运行
复制
    @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);
        }
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-09-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Spring Boot自定义配置项
    • 配置文件
    • @ConfigurationProperties 注解
    • 使用
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档