2016-09-06 46 views
0

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

回答

0

這是因爲你有一個無限循環,因此方法調用@PostConstruct永遠不會返回。

(它煤層怪我,那@PostConstruct作品與靜態方法,但也許這個作品)

因此,解決辦法是,你開始爲你守望者的新線程。你可以用不同的方式做到這一點:

  • 剛開始一個新的線程
  • 添加@Async該方法(我不知道這是否適用於@PostConstruct方法)(主要缺點是,這將啓動以前生產完整的應用程序上下文初始化)
  • 濫用​​註釋:@Scheduled(fixedDelay = Long.MAX_VALUE) - (優於@PostConstruct + @Async是:它的工作原理是肯定的,它只是開始後完全上下文初始化)
+0

感謝您的回覆:)我正在使用@Scheduled,它正在爲我工​​作 – vijendra

1

WatchService.take等待下一個手錶鍵:「檢索並移除下一個手錶鍵,等待沒有任何手錶存在。」

PostConstruct - 這是一個Java註釋,而不是Spring註解 - 「用於需要在依賴注入完成後執行以執行任何初始化的方法,必須在該類投入服務之前調用此方法「。基於這個文檔,似乎PostConstruct必須在bean投入服務之前返回(「在投入服務之前必須調用「)。

但您的PostConstruct方法不返回;所以PostConstruct不是你需要的。

您可能會考慮實施Spring InitializingBean接口,該接口提供回調方法afterPropertiesSet。它應該允許你啓動這種類型的服務方法。

否則,您可以查看Apache VFS2虛擬文件系統,其中包括文件夾監視器。這是我的項目使用的;在系統啓動時啓動觀察器非常容易;並且它還監視文件刪除,更新和創建事件(與Camel文件觀察器不同)。

+0

感謝您的回覆:) – vijendra