我試圖執行「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