簡體   English   中英

初始化StandardFileSystemManager的最佳實踐是什么

[英]What is the best practice to initialise 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()都會初始化管理器。 但是我打算一次初始化並在最后關閉。 這有可能嗎?

您可以使用單例設計模式來確保僅創建StandardFileSystemManager一個對象。

我看到您正在使用@Service批注。 我假設它從春天開始。 為什么不將StandardFileSystemManager注冊為spring bean,然后在MyFileService其自動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());
    }
}

並且您可以在標有@Configuration任何類中將StandardFileSystemManager注冊為bean,如下所示

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM