我正在尝试在 OSGi 中构建一个可以读取给定格式文件的服务。
服务接口如下所示:
public interface FileReaderService {
/**
* Reads the given file.
* @param filePath Path of the file to read
* @return the data object built from the file
* @throws IOException if there is an error while reading the file
*/
Data readFile(Path filePath) throws IOException;
/**
* Detects if the format of the provided file is supported.
* @param filePath the file to check
* @return true if the format of the file is supported, false otherwise
* @throws IOException if there is an error while reading the file
*/
boolean isFormatSupported(Path filePath) throws IOException;
}
Data 对象是一个类,它定义了要读取的文件的数据结构(它们应该包含相同类型的数据)。
这个想法是有不同的服务实现,例如:
public class TxtFileReader implements FileReaderService {
@Override
public Data readFile(Path filePath) throws IOException {
// Do something smart with the file
return data;
}
}
@Override
public boolean isFormatSupported(Path filePath) throws IOException {
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.txt");
return matcher.matches(filePath);
}
}
还可能有其他实现,例如 XmlFileReader、MdFileReader 等。
最后,我想要一个像这样的 FileReaderFactory:
@Component
public class FileReaderFactory implements FileReaderService {
private List<FileReaderService> availableServices = new ArrayList<>();
@Override
public Data readFile(Path filePath) throws IOException {
for (FileReaderService reader : availableServices) {
if (reader.isFormatSupported(filePath)) {
return reader.readFile(filePath);
}
}
return null;
}
@Override
public boolean isFormatSupported(Path filePath) throws IOException {
for (FileReaderService reader : availableServices) {
if (reader.isFormatSupported(filePath)) {
return true;
}
}
return false;
}
}
我想要的是 DS 在工厂列表中动态注入 FileReaderServices。根据提供的服务数量,我会支持(或不支持)给定的文件格式。
我的问题是:
1)这对DS可行吗?
2)如果是,如何使用DS注释来做到这一点?
3)如果没有,你会怎么做?
谢谢
编辑:我尝试了 Christian 的解决方案,但它没有工作(还)。完整代码可以在这里下载:https ://github.com/neopium/FileReader