多文件服务实现
通常会根据业务接入不同的服务商
以文件上传为例:
代码实现 定义接口,接口方法为基础功能:
public interface IFileService {
/**
* 上传
* @param file 需要上传的文件
* @return 上传成功/失败返回 。通常成功返回 可访问url
*/
String upload(MultipartFile file);
}
然后根据不同服务商分别实现
上传到本地路径
public class LocalFileServiceImpl implements IFileService {
String upload(MultipartFile file) {
//上传到本地路径
//此处省略业务代码
return "url";
}
}
上传到阿里云
public class AliYunFileServiceImpl implements IFileService {
String upload(MultipartFile file) {
//上传到阿里云
//此处省略业务代码
return "url";
}
}
上传到minio
public class MinIoFileServiceImpl implements IFileService {
String upload(MultipartFile file) {
//上传到minio
//此处省略业务代码
return "url";
}
}
配置实现类
@Configuration
public class FileAutoConfiguration {
/**
* 当 config.file.ali-yun.enable = true
* 并且 Spring 中不包含 IFileService 时生成Bean
* @return IFileService
*/
@Bean
@ConditionalOnProperty(prefix = "config.file.ali-yun", name = "enable")
@ConditionalOnMissingBean(IFileService.class)
public IFileService ossFileServiceImpl() {
return new AliYunFileServiceImpl();
}
/**
* 当 config.file.local.enable = true
* 并且 Spring 中不包含 IFileService 时生成Bean
* @return IFileService
*/
@Bean
@ConditionalOnProperty(prefix = "config.file.local", name = "enable")
@ConditionalOnMissingBean(IFileService.class)
public IFileService localFileServiceImpl() {
return new LocalFileServiceImpl();
}
/**
* 当 config.file.minio.enable = true
* 并且 Spring 中不包含 IFileService 时生成Bean
* @return IFileService
*/
@Bean
@ConditionalOnProperty(prefix = "config.file.minio", name = "enable")
@ConditionalOnMissingBean(IFileService.class)
public IFileService localFileServiceImpl() {
return new MinIoFileServiceImpl();
}
}
yaml
config:
file:
ali-yun:
enable: true
local:
enable: false
minio:
enable: false
通过以上配置 IFileService 的实现为 AliYunFileServiceImplL
后续如果有新的实现可自行实现 IFileService
上次更新: 2024/11/05, 08:29:31