gpt4 book ai didi

java - 带 Spring 的 WatchService

转载 作者:行者123 更新时间:2023-12-02 10:50:37 26 4
gpt4 key购买 nike

我正在尝试使用 spring 执行“WatchService”,但这看起来不可能,因为当我尝试在应用程序上下文时运行此服务,但当控制到达时,spring 上下文的加载将停止

key = watcher.take();

由于应用程序上下文的加载没有发生。

下面是完整代码

@Component
public class DirectoryWatchDemo {


@PostConstruct
public static void test(){
try {
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = Paths.get("C:/test");
dir.register(watcher, ENTRY_CREATE);

System.out.println("Watch Service registered for dir: " + dir.getFileName());

while (true) {
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException ex) {
return;
}

for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();

@SuppressWarnings("unchecked")
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path fileName = ev.context();

System.out.println(kind.name() + ": " + fileName);

if (kind == ENTRY_MODIFY &&
fileName.toString().equals("DirectoryWatchDemo.java")) {
System.out.println("My source file has changed!!!");
}
}

boolean valid = key.reset();
if (!valid) {
break;
}
}

} catch (IOException ex) {
System.err.println(ex);
}
}

}

我这样做是因为我不想手动执行“WatchService”。

最佳答案

这是因为你有一个无限循环,因此 @PostConstruct 的方法调用永远不会返回。

(我觉得很奇怪,@PostConstruct适用于静态方法,但也许这有效)

所以解决方案是为观察者启动一个新线程。您可以通过不同的方式来做到这一点:

  • 开始一个新话题
  • @Async 添加到该方法(我不知道这是否适用于 @PostConstruct 方法)(主要缺点是,这在完整的应用程序上下文之前启动正在初始化)
  • 滥用@Scheduler注释:@Scheduled(fixedDelay = Long.MAX_VALUE) -(相对于@PostConstruct+的优势@Async 是:它肯定有效,并且在完整的上下文初始化后启动)

关于java - 带 Spring 的 WatchService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39351863/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com