初始化StandardFileSystemManager

时间:2018-09-06 11:36:16

标签: java xcode spring-boot refactoring

目前,我的代码如下所示

@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()都会初始化管理器。但是我打算一次初始化并在最后关闭。 这可能吗?

1 个答案:

答案 0 :(得分:0)

您可以使用单例设计模式来确保仅创建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的任何类中将@Configuration注册为Bean

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