自学内容网 自学内容网

springBoot项目中,参数更改为配置文件

以下为obs的工具类更改为配置文件

1.新建一个类,存放基本的参数


import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Data
@Configuration
public class OBSProperties {
    @Value("${endpoint}")
    private   String endpoint;
    @Value("${accessKeyId}")
    private  String accessKeyId;
    @Value("${accessKeySecret}")
    private  String accessKeySecret;
    @Value("${bucketName}")
    private  String bucketName;

2.工具类改造后

public class ObsUtils {

    private static ObsUtils obs;

    public static ObsUtils getInstance() {
        if (obs == null) {
            obs = new ObsUtils();
        }
        return obs;
    }
    /**
     * 抽成共有的
     * @return
     */
    public static OBSProperties getOBSClient() {
        OBSProperties obsProperties= SpringUtil.getBean(OBSProperties.class);
        return  obsProperties;
    }

   
    private ObsClient getClient() {
        OBSProperties obsProperties= getOBSClient();
        // 初始化OSSClient
        ObsClient client = new ObsClient(obsProperties.getAccessKeyId(), obsProperties.getAccessKeySecret(), obsProperties.getEndpoint());
        return client;
    }
    private ObsClient getClient(String bucketName) {
        OBSProperties obsProperties= getOBSClient();
        // 初始化OSSClient
        ObsClient clientOut = new ObsClient(obsProperties.getAccessKeyId(), obsProperties.getAccessKeySecret(), obsProperties.getEndpoint());
        clientOut.createBucket(bucketName);
        return clientOut;
    }
  /**
     * 上传文件
     *
     * @param file     文件
     * @param fileName 文件存储名称
     * @return
     */
    public static PutObjectResult uploadFile(MultipartFile file, String key, String fileName)
            throws IOException {
        OBSProperties obsProperties= getOBSClient();
        // 初始化OSSClient
        ObsClient obsClient = new ObsClient(obsProperties.getAccessKeyId(), obsProperties.getAccessKeySecret(), obsProperties.getEndpoint());

        InputStream content = file.getInputStream();

        String objectKey= key+ "/"+ fileName;
        PutObjectRequest request =new  PutObjectRequest(obsProperties.getBucketName(),  objectKey, content);

        try {
            PutObjectResult result = obsClient.putObject(request);
            return  result;
        } catch (ObsException e) {
            logger.error("Error uploading file: " + e.getErrorCode() + " - " + e.getErrorMessage());
        } finally {
            obsClient.close();
        }
        return  null;
    }


原文地址:https://blog.csdn.net/man_18483633325/article/details/143774917

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