java - 初始化 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
?默认情况下,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;
}
推荐阅读
- javascript - vim中的javascript AMD标签?
- pine-script - 我们可以使用 TradingView 访问 pine 脚本中的交易面板选项卡吗?
- java - 仅使用 1、2、3 步即可达到第 n 步
- java - Windows 上的字符编码混淆
- ios - 交换 UITextField 的 isEnabled 更改背景颜色以及如何防止它
- python - Pandas 对 bp 进行分组,根据条件过滤和提取行
- java - 我怎样才能拥有这两个构造函数?
- python - 在 time.sleep(10) 之后运行时方法内的变量不更新 - python
- javascript - 使用 jsforce 无法通过 SalesForce Date 对象查询
- python-3.x - Django 动态模型表单