springboot检测配置是否存在,如果存在则返回,不存在则提示新增
我这里是以七牛为例子
在yml中添加七牛的相关配置
qiniu: #七牛的相关配置 accessKey: your_access_key secretKey: your_secret_key bucket: your_bucket_name domain: your_domain
对应在给配置文件来一个相应的实体类QiniuConfig
@Component
@ConfigurationProperties(prefix = "qiniu")//获取配置
public class QiniuConfig {
//七牛云提供的密钥对,用于身份验证
private String accessKey;
private String secretKey;
//存储空间名称
private String bucket;
//存储空间绑定的域名
private String domain;
public String getAccessKey() {
return accessKey;
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public String getBucket() {
return bucket;
}
public void setBucket(String bucket) {
this.bucket = bucket;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public QiniuConfig() {
}
public QiniuConfig(String domain, String bucket, String secretKey, String accessKey) {
this.domain = domain;
this.bucket = bucket;
this.secretKey = secretKey;
this.accessKey = accessKey;
}
}
在补全相应的service
@Service
public class CommonServiceImpl {
private final QiniuConfig qiniuConfig;
@Autowired
public CommonServiceImpl(QiniuConfig qiniuConfig) {
this.qiniuConfig = qiniuConfig;
}
/**
* 检查七牛云配置并返回相应信息。
*
* @return 如果配置存在,则返回配置信息;如果不存在,则提示添加配置。
*/
public R<QiniuConfig> getQiniuConfig() {
if (isQiniuConfigured()) {
return R.success(qiniuConfig);
} else {
return R.error("请在配置文件中添加七牛云的相关配置。");
}
}
/**
* 检查是否已配置七牛云。
*
* @return 如果配置存在返回true,否则返回false。
*/
private boolean isQiniuConfigured() {
return qiniuConfig != null &&
qiniuConfig.getAccessKey() != null && !qiniuConfig.getAccessKey().isEmpty() &&
qiniuConfig.getSecretKey() != null && !qiniuConfig.getSecretKey().isEmpty() &&
qiniuConfig.getBucket() != null && !qiniuConfig.getBucket().isEmpty() &&
qiniuConfig.getDomain() != null && !qiniuConfig.getDomain().isEmpty();
}
}
重点在这里
在补全相关的controller
/**
* 公共配置controller
*/
@Controller
@ResponseBody
@RequestMapping("/commonConfig")
@Tag(name = "公共配置controller")
public class CommonController {
@Autowired
private CommonServiceImpl commonService;
@Operation(summary = "获取七牛的相关配置", description = "获取七牛的相关配置")
@GetMapping("/getQiniu")
public R getQiniuConfig() {
return commonService.getQiniuConfig();
}
}
最后测试