无锡手机网站制作,上海哪家优化公司好,做软件下载网站违法吗,医院网站建设细节问题分析
在往期的配置参数的文章中#xff0c;对于阿里云OSS的参数时设置在yml配置文件中#xff0c;然后使用Value#xff08;”${}“#xff09;对参数进行赋值#xff0c;具体如下#xff1a; 此种方法比较繁琐
问题解决
使用注解
Data 为变量自动生成get/set方…问题分析
在往期的配置参数的文章中对于阿里云OSS的参数时设置在yml配置文件中然后使用Value”${}“对参数进行赋值具体如下 此种方法比较繁琐
问题解决
使用注解
Data 为变量自动生成get/set方法Component 将参数交给IOC容器管理成为bean对象ConfigurationProperties 指定变量在yml配置文件中的前缀
具体思路创建一个实体类用于封装需要用到的属性值在需要使用的程序中通过注入实体类对象将调用get方法即可获取对应的属性值
具体代码
实体类 package com.example.tlias.pojo;import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;Data // 自动生成get/set方法
Component // 注入IOC容器生成Bean对象
ConfigurationProperties(prefix aliyun.oss) // 设置属性前缀便于找到对应在yml映射文件中的属性位置
public class AliOSSProperties {private String endpoint;private String accessKeyId;private String accessKeySecret;private String bucketName;
}映射文件 调用属性程序 package com.example.tlias.utils;import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.example.tlias.pojo.AliOSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;import java.io.*;
import java.util.UUID;/*** 阿里云 OSS 工具类*/
Component
public class AliOSSUtils {// // todo 指定OSS服务地址
// Value(${aliyun.oss.endpoint})
// private String endpoint;
// // todo 设置密钥账号和密码
// Value(${aliyun.oss.accessKeyId})
// private String accessKeyId;
// Value(aliyun.oss.accessKeySecret)
// private String accessKeySecret;
// // todo 设置文件存储buket
// Value(aliyun.oss.bucketName)
// private String bucketName;// todo 注入实体类对象Autowiredprivate AliOSSProperties aliOSSProperties;/*** 实现上传图片到OSS*/public String upload(MultipartFile file) throws IOException {// todo 获取已经封装了的属性值String endpoint aliOSSProperties.getEndpoint();String accessKeyId aliOSSProperties.getAccessKeyId();String accessKeySecret aliOSSProperties.getAccessKeySecret();String bucketName aliOSSProperties.getBucketName();// 获取上传的文件的输入流InputStream inputStream file.getInputStream();// 避免文件覆盖String originalFilename file.getOriginalFilename();String fileName UUID.randomUUID().toString() originalFilename.substring(originalFilename.lastIndexOf(.));//上传文件到 OSSOSS ossClient new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);ossClient.putObject(bucketName, fileName, inputStream);//文件访问路径String url endpoint.split(//)[0] // bucketName . endpoint.split(//)[1] / fileName;// 关闭ossClientossClient.shutdown();return url;// 把上传到oss的路径返回}}ConfigurationProperties和Value的比较
相同点 都是用来注入外部配置的属性的不同点 Value注解只能一个一个进行外部属性的注入ConfigurationProperties可以批量地将外部地属性配置注入到bean对象地属性中