java实现oss上传文件单例模式写法
时间: 2025-01-05 08:07:21 浏览: 27
在Java中实现OSS(Object Storage Service)上传文件的单例模式,通常是为了保证在整个应用中只有一个实例,并提供统一的操作接口。下面是一个简单的Spring Boot风格的阿里云OSS上传文件单例模式示例:
```java
import com.aliyun.oss.OSS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component("ossClient")
public class OssSingleton {
private static volatile OssSingleton instance;
private OSS ossClient;
// 防止直接new创建对象,通过getInstance()获取唯一实例
private OssSingleton() {
@Autowired
private void init(AliyunCredentials credentials) {
String endpoint = "your_oss_endpoint";
String bucketName = "your_bucket_name";
ossClient = new OSS(credentials.getAccessKeyId(), credentials.getAccessKeySecret(), endpoint, bucketName);
}
}
public static OssSingleton getInstance() {
if (instance == null) {
synchronized (OssSingleton.class) {
if (instance == null) {
instance = new OssSingleton();
}
}
}
return instance;
}
public OSS getClient() {
return ossClient;
}
阅读全文