我试图执行“WatchService”弹簧,但它正在寻找不可能的,因为当我试图运行的应用程序上下文,但是Spring上下文的装载时该服务成为停止时控制来在WatchService弹簧
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”。
感谢您的回复:)我正在使用@Scheduled,它正在为我工作 – vijendra