在springboot项目中使用oss单例模式上传文件,优化上面代码
时间: 2025-06-09 12:01:44 浏览: 9
在Spring Boot项目中,为了优化阿里云OSS上传文件的单例模式,我们可以利用Spring的依赖注入和懒汉式加载机制。这样可以避免在初始化阶段就创建OSS客户端,直到真正需要使用时才实例化,降低内存占用。以下是优化后的代码:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
@Lazy // 注解表示懒加载
@Component("ossClient")
public class OssSingleton {
private OSS ossClient; // 私有变量,推迟到实际使用时初始化
public static OssSingleton getInstance() {
if (instance == null) { // 只有当第一次请求时才会初始化
synchronized (OssSingleton.class) {
if (instance == null) {
instance = new OssSingleton();
}
}
}
return instance;
}
@Autowired
public void setOssClient(AliyunCredentials credentials) {
String endpoint = "your_oss_endpoint";
String bucketName = "your_bucket_name";
this.ossClient = new OSS(credentials.getAccessKeyId(), credentials.getAccessKeySecret(), endpoint, bucketName);
}
public OSS getClient() {
return ossClient;
}
阅读全文
相关推荐















