首页 > 解决方案 > 初始化 StandardFileSystemManager 的最佳实践是什么

问题描述

目前,我的代码如下

@Service
public class MyFileService {
    private StandardFileSystemManager manager = new StandardFileSystemManager();

    public List<FileObject> listRemoteFiles() {
        try {
            manager.init();

            manager.resolveFile(someURL);


        } finally {
            manager.close();
        }
        return Arrays.stream(remoteFiles)
                     .collect(Collectors.toList());
    }
}

但是我发现有时候 manager.init() 会因为多次注册而抛出异常

FileSystemException:为 URL 方案“文件”注册了多个提供程序。

是否有创建此 StandardFileSystemManager 的最佳实践?所以它只注册 1 个提供者?

我猜每次我调用 listRemoteFiles() 它都会初始化管理器。但我打算初始化一次并在最后关闭。这可能吗?

标签: javaxcodespring-bootrefactoring

解决方案


您可以使用单例设计模式来确保只StandardFileSystemManager创建一个对象。

我看到你正在使用@Service注释。我假设它从春天开始。你为什么不注册StandardFileSystemManager为spring bean然后自动装配它MyFileService?默认情况下,spring bean 是单例的。所以你的代码看起来像

@Service
public class MyFileService {

    private final StandardFileSystemManager manager;

    @Autowired
    public MyFileService(StandardFileSystemManager manager) {
        this.manager = manager;
    }

    public List<FileObject> listRemoteFiles() {
        try {
            manager.resolveFile(someURL);
        } finally {
            manager.close();
        }

        return Arrays.stream(remoteFiles)
                     .collect(Collectors.toList());
    }
}

并且您可以在任何标记为如下StandardFileSystemManager的类中注册为 bean@Configuration

@Bean
public StandardFileSystemManager manager() {
    StandardFileSystemManager manager = new StandardFileSystemManager();
    manager.init(); 
    return manager;
}

推荐阅读