2013-12-16 96 views
2

我想在我的Spring應用程序中使用Java 7 WatchService來監視目錄中的服務。這個想法是,當目錄中的文件被更改時,通過WebSockets連接的客戶端會得到通知。春季長期服務?

如何獲得一個bean作爲服務在自己的線程中運行?

+2

使用帶'@ Async'註釋的方法創建一個bean。在異步配置的Spring上下文中創建bean並調用該方法。 –

+0

看看Spring集成。 http://www.java-allandsundry.com/2013/05/spring-integration-file-polling-and.html –

回答

4

你所尋找的是Asynchronous execution.有了一個正確配置的情況下(見鏈接),你聲明一個類,像這樣在你做someAsyncMethod()

@Component 
public class AsyncWatchServiceExecutor { 
    @Autowired 
    private WatchService watchService; // or create a new one here instead of injecting one 

    @Async 
    public void someAsyncMethod() { 
     for (;;) { 
      // use WatchService 
     } 
    } 
} 

一切都將在一個單獨的線程發生。你只需要調用一次。

ApplicationContext context = ...; // get ApplicationContext 
context.getBean(AsyncWatchServiceExecutor.class).someAsyncMethod(); 

Oracle documentation描述使用WatchService


如果沒有你的ApplicationContext直接訪問,可以在其他一些豆注入的bean並調用它的@PostConstruct方法。

@Component 
public class AsyncInitializer { 
    @Autowired 
    private AsyncWatchServiceExecutor exec; 

    @PostConstruct 
    public void init() { 
     exec.someAsyncMethod(); 
    } 
} 

小心使用哪種代理策略(JDK或CGLIB)。

+0

感謝您的詳細解答。我對Spring仍然很陌生,所以這非常有幫助。 –

+0

@Joe不客氣。請小心閱讀儘可能多的鏈接文檔。併發不是一個簡單的概念。 –

+0

感謝編輯 – nurgasemetey