application.yml:
# 阿里云OSS
aliyun:
oss:
file:
endpoint: oss-cn-beijing.aliyuncs.com # 对应公网endpoint地址
accessKeyId: LTAI
accessKeySecret: Pm1
bucketName: w #可以代码层面实现
folder: active #保存文件夹路径
一、第一种 使用@PropertySource
@Component
@PropertySource(value = "classpath:application.yml")
public class AliConfig implements InitializingBean {
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
@Value("${aliyun.oss.file.accessKeyId}")
private String accessKeyId;
@Value("${aliyun.oss.file.accessKeySecret}")
private String accessKeySecret;
@Value("${aliyun.oss.file.bucketName}")
private String bucketName;
@Value("${aliyun.oss.file.folder}")
private String folder;
public static String END_POINT;
public static String ACCESS_KEY_ID;
public static String ACCESS_KEY_SECRET;
public static String BUCKET_NAME;
public static String FOLDER;
@Override
public void afterPropertiesSet() {
END_POINT = endpoint;
ACCESS_KEY_ID = accessKeyId;
ACCESS_KEY_SECRET = accessKeySecret;
BUCKET_NAME = bucketName;
FOLDER = folder;
}
}
二、第二种 直接在类中读取
@Slf4j
@RestController
@RequestMapping("/boot")
public class Controller {
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
@Value("${aliyun.oss.file.accessKeyId}")
private String accessKeyId;
@GetMapping("getvalue")
public void firstConfInject(){
log.info("first conf inject: {},{}",endpoint,accessKeyId);
}
}
三、第三种 使用@ConfigurationProperties
@Component
@ConfigurationProperties(prefix = "aliyun.oss.file")
public class AliOSSConfig {
private static String endpoint;
private static String accessKeyId;
private static String accessKeySecret;
private static String bucketName;
private static String folder;
public static String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
AliOSSConfig.endpoint = endpoint;
}
public static String getAccessKeyId() {
return accessKeyId;
}
public void setAccessKeyId(String accessKeyId) {
AliOSSConfig.accessKeyId = accessKeyId;
}
public static String getAccessKeySecret() {
return accessKeySecret;
}
public void setAccessKeySecret(String accessKeySecret) {
AliOSSConfig.accessKeySecret = accessKeySecret;
}
public static String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
AliOSSConfig.bucketName = bucketName;
}
public static String getFolder() {
return folder;
}
public void setFolder(String folder) {
AliOSSConfig.folder = folder;
}
}