我正在使用SpringBoot来监视文件夹中的新文件。配置看起来像这样:
@Configuration
@ManagedResource
public class FileWatcherConfig {
Logger log = LoggerFactory.getLogger(FileWatcherConfig.class);
@Value("${filewatcher.path:C:\\test}")
String pathname;
@Bean
public FileSystemWatcher fileSystemWatcher() {
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(true, Duration.ofMillis(5000L), Duration.ofMillis(3000L));
fileSystemWatcher.addSourceDirectory(new File(pathname));
fileSystemWatcher.addListener(new MyFileChangeListener());
fileSystemWatcher.start();
log.info("started fileSystemWatcher");
return fileSystemWatcher;
}
@PreDestroy
public void onDestroy() {
fileSystemWatcher().stop();
}
@ManagedOperation
public void setPathname(String pathname) {
this.pathname = pathname;
}
@ManagedAttribute
public String getPathname(){
return pathname;
}
}
尽管我可以在运行时使用jconsole更改路径名值,但应用程序仍会监视初始文件夹。
当您通过JMX更改路径时,所要做的就是为pathname
bean中的FileWatcherConfig
字段分配一个新值。
您需要编写其他代码来在更改后用新路径更新FileSystemWatcher
bean,包括可能停止它,删除当前侦听器,然后更新源目录。