简体   繁体   English

Spring Bean在自己的线程中运行

[英]Spring Bean running in its own thread

Within my web application, I am trying to create a directory polling bean using Java SDK7 WatchService. 在我的Web应用程序中,我尝试使用Java SDK7 WatchService创建目录轮询bean。 What I would like to achieve is to run this bean in its own thread so that it does not block the application. 我想要实现的是在自己的线程中运行此bean,以便它不会阻止应用程序。 Something like: 就像是:

  <bean id="directoryPoller" class="org...MyDirectoryPoller" scope="thread"/>

I am afraid you will have to create this thread manually with Spring: 我担心你必须用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"/>

The WatchServiceRunnableWrapper is simple: 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. 我还没有对它进行测试,但它或多或少应该正常工作和关闭。

I'm not familiar with Java 7's WatchService, but you could use Springs' scheduling support for this. 我不熟悉Java 7的WatchService,但您可以使用Springs的调度支持 Here's yet another tutorial and googling for something like Spring Scheduled probably finds loads more. 这是另一个教程和google搜索类似Spring Scheduled可能会发现更多的负载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM