springboot 项目读取默认配置

本文介绍如何在SpringBoot项目中优雅地读取配置,通过CosConfig类实现在配置文件存在时读取其值,不存在时使用默认配置。CosConfig类通过@ConfigurationProperties注解与配置文件关联,同时定义了默认值。

项目需求

配置文件中有对应key-value的配置时,则读取配置文件中的配置,如果没有对应的key-value时则读取默认的配置

配置类 CosConfig.java 采用如下方式即可实现

package com.dongao.support.config;

/**
 * 腾讯云上传参数
 * @author: dongao
 * @create: 2019/10/16
 */
@Component
@ConfigurationProperties(prefix = "cos")
public class CosConfig {

    //默认值
    private String secretId = "123456789abcdefg";

    private String secretKey = "123456789abcdefghijklmn";

    private String region = "ap-where";

    private String bucketName = "abc-12557870610";

    private String projectName = "test";

    private String common = "common";

    private String imageSize = "2";

    public String getSecretId() {
        return secretId;
    }

    public void setSecretId(String secretId) {
        this.secretId = secretId;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public String getRegion() {
        return region;
    }

    public void setRegion(String region) {
        this.region = region;
    }

    public String getBucketName() {
        return bucketName;
    }

    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }

    public String getProjectName() {
        return projectName;
    }

    public void setProjectName(String projectName) {
        this.projectName = projectName;
    }

    public String getCommon() {
        return common;
    }

    public void setCommon(String common) {
        this.common = common;
    }

    public String getImageSize() {
        return imageSize;
    }

    public void setImageSize(String imageSize) {
        this.imageSize = imageSize;
    }
}

应用工具类

package com.dongao.support.utils;

import com.dongao.support.config.CosConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/**
 * 上传工具类
 * @author: dongao
 * @create: 2019/10/16
 */
public class CosClientUtil {

    private static CosConfig cosConfig = SpringUtils.getBean(CosConfig.class);

    /**初始化密钥信息*/
    private COSCredentials cred = new BasicCOSCredentials(cosConfig.getSecretId(), cosConfig.getSecretKey());
    /**初始化客户端配置,设置bucket所在的区域*/
    private ClientConfig clientConfig = new ClientConfig(new Region(cosConfig.getRegion()));
    /**初始化cOSClient*/
    private COSClient cOSClient = new COSClient(cred, clientConfig);

    /**
     * 上传图片
     * @param file
     * @param businessName
     * @return
     * @throws Exception
     */
    public String uploadImgToCos(MultipartFile file, String businessName) throws Exception {
        int imageSize = Integer.parseInt(cosConfig.getImageSize());
        int maxSize = imageSize << 20;
        if (file.getSize() > maxSize) {
            throw new Exception("上传图片大小不能超过"+imageSize+"M!");
        }
        if (StringUtils.isEmpty(businessName)) {
            businessName = cosConfig.getCommon();
        }
        //生成文件夹层级
        Calendar cale = Calendar.getInstance();
        int year = cale.get(Calendar.YEAR);
        SimpleDateFormat sdf = new SimpleDateFormat("MM");
        Date dd  = cale.getTime();
        String month = sdf.format(dd);
        String folderName = cosConfig.getProjectName()+"/image/"+businessName+"/"+year+"/"+month+"/";
        //图片名称
        String originalFilename = file.getOriginalFilename();
        Random random = new Random();
        //生成新的图片名称(随机数0-9999+系统当前时间+上传图片名)
        String name;
        if (originalFilename.lastIndexOf(".") != -1) {
            name = random.nextInt(10000) + System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
        }else {
            String extension = FileUploadUtils.getExtension(file);
            name = random.nextInt(10000) + System.currentTimeMillis() + "." + extension;
        }
        //生成对象键
        String key = folderName+name;
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFileToCos(inputStream, key);
            //return "http://" + cosConfig.getBucketName() + ".cos."+cosConfig.getRegion()+".myqcloud.com/" + key;
            return key;
        } catch (Exception e) {
            throw new Exception("图片上传失败");
        }
    }

    /**
     * 上传到COS服务器 如果同名文件会覆盖服务器上的
     * @param instream
     * @param key
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public String uploadFileToCos(InputStream instream, String key) {
        String etag = "";
        try {
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            // 设置输入流长度为500
            objectMetadata.setContentLength(instream.available());
            // 设置 Content type
            objectMetadata.setContentType(getcontentType(key.substring(key.lastIndexOf("."))));
            // 上传文件
            PutObjectResult putResult = cOSClient.putObject(cosConfig.getBucketName(),  key, instream, objectMetadata);
            etag = putResult.getETag();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (instream != null) {
                    //关闭输入流
                    instream.close();
                }
                // 关闭客户端(关闭后台线程)
                cOSClient.shutdown();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return etag;
    }

    /**
     * Description: 判断Cos服务文件上传时文件的contentType
     * @param filenameExtension 文件后缀
     * @return String
     */
    public String getcontentType(String filenameExtension) {
        String bmp = "bmp";
        if (bmp.equalsIgnoreCase(filenameExtension)) {
            return "image/bmp";
        }
        String gif = "gif";
        if (gif.equalsIgnoreCase(filenameExtension)) {
            return "image/gif";
        }
        String jpeg = "jpeg";
        String jpg = "jpg";
        String png = "png";
        if (jpeg.equalsIgnoreCase(filenameExtension) || jpg.equalsIgnoreCase(filenameExtension)
                || png.equalsIgnoreCase(filenameExtension)) {
            return "image/jpeg";
        }
        String html = "html";
        if (html.equalsIgnoreCase(filenameExtension)) {
            return "text/html";
        }
        String txt = "txt";
        if (txt.equalsIgnoreCase(filenameExtension)) {
            return "text/plain";
        }
        String vsd = "vsd";
        if (vsd.equalsIgnoreCase(filenameExtension)) {
            return "application/vnd.visio";
        }
        String pptx = "pptx";
        String ppt = "ppt";
        if (pptx.equalsIgnoreCase(filenameExtension) || ppt.equalsIgnoreCase(filenameExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        String docx = "docx";
        String doc = "doc";
        if (docx.equalsIgnoreCase(filenameExtension) || doc.equalsIgnoreCase(filenameExtension)) {
            return "application/msword";
        }
        String xml = "xml";
        if (xml.equalsIgnoreCase(filenameExtension)) {
            return "text/xml";
        }
        String mp4 = ".mp4";
        if (mp4.equalsIgnoreCase(filenameExtension)) {
            return "application/octet-stream";
        }
        return "image/jpeg";
    }

}

注: 如上,在配置文件中有对应配置时则读取配置文件中的值,在配置文件中无对应值时则应用默认配置

Spring Boot 默认读取配置文件名称为 `application.properties` 或 `application.yml`,这些文件通常用于存储应用程序的配置参数。 关于配置文件的位置,Spring Boot 提供了多个默认的查找路径,优先级从高到低依次如下: 1. 当前目录下的 `/config` 子目录(例如:`file:./config/`)。 2. 当前目录(例如:`file:./`)。 3. classpath 根目录下的 `/config` 包(例如:`classpath:/config/`)。 4. classpath 根目录(例如:`classpath:/`)[^1]。 这些路径的优先级意味着,如果在多个位置存在同名的配置文件,Spring Boot 会优先使用优先级较高的位置中的文件。例如,当前目录下的 `application.properties` 文件会覆盖 classpath 中的同名文件。 这种设计允许开发者在不同环境中灵活配置应用程序的行为,例如在开发环境中使用 `classpath` 中的配置文件,而在生产环境中通过外部的 `file:./config/` 目录提供特定的配置。 ### 读取配置文件内容 Spring Boot 支持多种方式读取配置文件中的参数,常见的方法包括: - 使用 `@Value` 注解注入单个配置项: ```java @Value("${person.name}") private String name; ``` - 使用 `@ConfigurationProperties` 注解绑定配置到一个 Java Bean: ```java @ConfigurationProperties(prefix = "person") public class Person { private String name; private int age; // getters and setters } ``` - 使用 `Environment` 接口获取配置值: ```java @Autowired private Environment env; public void testProp() { String emailForm = env.getProperty("email.form"); } ``` 这些方式使得配置文件的内容可以方便地在应用程序中使用,并且可以根据需求选择合适的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

csdn565973850

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值