我正在编写一个Spring Boot应用程序来监视目录并处理添加到其中的文件。我在配置类中使用WatchService注册了该目录:
@Configuration
public class WatchServiceConfig {
private static final Logger logger = LogManager.getLogger(WatchServiceConfig.class);
@Value("${dirPath}")
private String dirPath;
@Bean
public WatchService register() {
WatchService watchService = null;
try {
watchService = FileSystems.getDefault().newWatchService();
Paths.get(dirPath).register(watchService, ENTRY_CREATE);
logger.info("Started watching \"{}\" directory ", dlsDirPath);
} catch (IOException e) {
logger.error("Failed to create WatchService for directory \"" + dirPath + "\"", e);
}
return watchService;
}
}
如果在注册目录时失败,我希望能够优雅地中止Spring Boot启动。有人知道我该如何做吗?
System.exit(SIGNUM)
吗? - TurtleSystem.stop()
会立即终止JVM。 - Zhubin SalehiRuntimeException
呢? - Turtleregister
的bean,这对于WatchService
bean来说是一个糟糕的名称。我强烈建议将方法重命名为更适合bean名称的内容,例如public WatchService watchService() { ... }
。 - M. Justin