Spring Bean在自己的线程中运行 [英] Spring Bean running in its own thread
本文介绍了Spring Bean在自己的线程中运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的Web应用程序中,我正在尝试使用Java SDK7 WatchService创建目录轮询bean。我想要实现的是在自己的线程中运行此bean,以便它不会阻止应用程序。类似于:
Within my web application, I am trying to create a directory polling bean using Java SDK7 WatchService. What I would like to achieve is to run this bean in its own thread so that it does not block the application. Something like:
<bean id="directoryPoller" class="org...MyDirectoryPoller" scope="thread"/>
推荐答案
恐怕你必须手动创建这个线程使用Spring:
I am afraid you will have to create this thread manually with Spring:
<bean id="pollThread" class="java.lang.Thread" init-method="start" destroy-method="interrupt">
<constructor-arg ref="watchServiceRunnableWrapper"/>
</bean>
<bean id="watchServiceRunnableWrapper" class="WatchServiceRunnableWrapper">
<constructor-arg ref="watchService"/>
</bean>
<bean id="WatchService" class="java.nio.file.WatchService" destroy-method="close"/>
WatchServiceRunnableWrapper
很简单:
public class WatchServiceRunnableWrapper implements Runnable {
private WatchService WatchService;
public WatchServiceRunnableWrapper(WatchService watchService) {
this.watchService = watchService;
}
public void run() {
watchService.poll();
//
}
}
我还没有测试过它,但它或多或少应该优雅地工作和关闭。
I haven't tested it, but it more-or-less should work and shutdown gracefully.
这篇关于Spring Bean在自己的线程中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文