Change dynamically (using JMX) the folder being watched for new files

Viewed 104

I'm using SpringBoot to watch a folder for new files. The configuration looks like this:

@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;
    }
}

Although I'm able to change the pathname value in runtime using jconsole the application still watches the initial folder.

1 Answers

When you change the path via JMX, all that's doing is assigning a new value to the pathname field in the FileWatcherConfig bean.

You'll need to write additional code to update the FileSystemWatcher bean with the new path after it changes -- including potentially stopping it, removing the current listener, and then updating the source directory.

Related