我想在我的Spring应用程序中提供一个服务,该服务使用Java 7 WatchService监视目录中的更改。想法是,当目录中的文件更改时,将通知通过WebSockets连接的客户端。
我如何使bean在其自己的线程中作为服务运行?
您正在寻找的是异步执行。使用正确配置的上下文(请参阅链接),您可以像这样声明一个类
@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 } } }
您所做的一切都someAsyncMethod()
将在单独的线程中发生。您所要做的就是调用一次。
ApplicationContext context = ...; // get ApplicationContext context.getBean(AsyncWatchServiceExecutor.class).someAsyncMethod();
使用WatchService
如描述Oracle文档。
如果您没有直接访问的权限ApplicationContext
,则可以将Bean注入到其他Bean中,并在@PostConstruct
方法中调用它。
@Component public class AsyncInitializer { @Autowired private AsyncWatchServiceExecutor exec; @PostConstruct public void init() { exec.someAsyncMethod(); } }
小心使用哪种代理策略(JDK或CGLIB)。