在SpringBoot项目中使用OSS存储上传的图片,需要配置OSS设置信息。避免对象的重复创建,确保一个类只有一个实例,并提供一个全局访问点来访问该实例,于是用到了单例模式,这里复习一下单例模式。
单线程----懒汉式
@Data
@Component
@ConfigurationProperties(prefix = "aliyun.oss")
public class AliyunOssUtil {
private static String endpoint;
private static String accessKeyId;
private static String accessKeySecret;
private String bucketName;
private static OSS ossClient = null;
public static OSS getInstance(){
if (null == ossClient){
ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
}
return ossClient;
}
}
多线程----懒汉式
@Data
@Component
@ConfigurationProperties(prefix = "aliyun.oss")
public class AliyunOssUtil {
private static String endpoint;
private static String accessKeyId;
private static String accessKeySecret;
private String bucketName;
private static OSS ossClient = null;
public static synchronized OSS getInstance(){
if (null == ossClient){
ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
}
return ossClient;
}
双重检查锁----懒汉式
@Data
@Component
@ConfigurationProperties(prefix = "aliyun.oss")
public class AliyunOssUtil {
private static String endpoint;
private static String accessKeyId;
private static String accessKeySecret;
private String bucketName;
private static OSS ossClient = null;
public static OSS getInstance(){
if (null == ossClient){
synchronized (AliyunOssUtil.class){
if (null == ossClient) {
ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
}
}
}
return ossClient;
}
}
静态内部类----懒汉式(推荐)
@Data
@Component
@ConfigurationProperties(prefix = "aliyun.oss")
public class AliyunOssUtil {
private static String endpoint;
private static String accessKeyId;
private static String accessKeySecret;
private String bucketName;
private static final class OssClientHolder {
static final OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
}
public static OSS getInstance(){
return OssClientHolder.ossClient;
}
}
饿汉式,在类初始化时已经自行实例化。
@Data
@Component
@ConfigurationProperties(prefix = "aliyun.oss")
public class AliyunOssUtil {
private static String endpoint;
private static String accessKeyId;
private static String accessKeySecret;
private String bucketName;
private static final OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
public static OSS getInstance(){
return ossClient;
}
}
标签:SpringBoot,OSS,ossClient,private,accessKeySecret,static,设计模式,String
From: https://www.cnblogs.com/poteitoutou/p/18016200