title: WatchService with spring
body: <p>I am trying to execute "WatchService" with spring but it is looking impossible because when  I am  trying to run this service at the time of application context but loading of spring context becoming stop when control come at </p>
  
  <pre class="lang-html prettyprint-override"><code>key = watcher.take();
  </code></pre>
  
  
  
  <p>due to this loading of application context is not happening.</p>
  
  <p>below is the full code</p>
  
  <pre class="lang-html prettyprint-override"><code>@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&lt;?&gt; event : key.pollEvents()) {
                      WatchEvent.Kind&lt;?&gt; kind = event.kind();
  
                      @SuppressWarnings("unchecked")
                      WatchEvent&lt;Path&gt; ev = (WatchEvent&lt;Path&gt;) event;
                      Path fileName = ev.context();
  
                      System.out.println(kind.name() + ": " + fileName);
  
                      if (kind == ENTRY_MODIFY &amp;&amp;
                              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);
          }
      }
  
  }
  </code></pre>
  
  
  
  <p>I am doing in this way because I do not want to execute "WatchService" manually.</p>