闲碎记事本 闲碎记事本
首页
  • JAVA
  • Cloudflare
  • 学完再改一遍UI
友链
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

YAN

我要偷偷记录...
首页
  • JAVA
  • Cloudflare
  • 学完再改一遍UI
友链
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • java

    • SpringBoot

      • 指定文件启动
      • 多文件服务实现
      • JAVA命令行参数以及配置加载顺序
    • SpringSecurity

    • MybatisPlus

    • Netty

    • sip

    • 其他

  • linux

  • docker

  • redis

  • nginx

  • mysql

  • 其他

  • 环境搭建

  • 知识库
  • java
  • SpringBoot
Yan
2023-03-06

多文件服务实现

通常会根据业务接入不同的服务商

以文件上传为例:

代码实现 定义接口,接口方法为基础功能:

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

上次更新: 2025/05/14, 01:34:05
指定文件启动
JAVA命令行参数以及配置加载顺序

← 指定文件启动 JAVA命令行参数以及配置加载顺序→

最近更新
01
Caddy操作指南
04-25
02
Swap空间
04-22
03
Alist使用
04-21
更多文章>
Theme by Vdoing | Copyright © 2022-2025 YAN | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式