我有一个简单的应用程序,我想用它来监视一个目录,到目前为止,我使用的方法是使用WatchService类:
ApplicationClass:
@SpringBootApplication
public class MmsdirectorywatcherApplication {
public static void main(String[] args) {
SpringApplication.run(MmsdirectorywatcherApplication.class, args);
}
@Autowired
DirectoryWatcher directoryWatcher;
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
directoryWatcher.startWatching();
};
}
}DirectoryWatcher:
@Component
public class DirectoryWatcher {
WatchService watchService;
Path path;
private String watcherDiretory;
public DirectoryWatcher() {
}
@Value("${mms.directorywatcher.directory}")
public void setWatcherDiretory(String watcherDiretory) {
this.watcherDiretory = watcherDiretory;
}
public void startWatching(){
path = Paths.get(watcherDiretory);
try{
watchService
= FileSystems.getDefault().newWatchService();
path.register(
watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println(
"Event kind:" + event.kind()
+ ". File affected: " + event.context() + ".");
}
key.reset();
}
}
catch (IOException ex){
}
catch (InterruptedException ex){
}
}
}这运行得很好,但我想测试一下applicationStarted是否正确,下面是测试:
@SpringBootTest(classes = {MmsdirectorywatcherApplication.class})
class MmsdirectorywatcherApplicationTests {
@Autowired
private DirectoryWatcher directoryWatcher;
@Test
void contextLoads() {
assertNotNull(directoryWatcher);
}
}当我运行测试时,它似乎被卡住了,好像有什么东西阻碍了它的完成。可能是watchService本身,但我不确定如何解决这个问题,因为我确实希望最终测试是否调用了startWatching。
感谢您抽出时间
发布于 2020-11-10 04:25:22
您的上下文启动调用startWatching(),而该函数永远不会返回。请注意,watchService.take()将阻塞,直到事件传入。
https://stackoverflow.com/questions/64758476
复制相似问题