jonD02 jonD02 - 1 month ago 10
Java Question

Spring Boot - Update ResourceHandlerRegistry without restarting app

In my Spring Boot app that will be running locally the user needs to be able to drag photos into the web page from the operating system and have them displayed. The path on the OS to the files can be set at startup with:

@SpringBootApplication
public class UploaderApplication extends WebMvcConfigurerAdapter {

private String workingDir = "/Users/example/Desktop/";

public static void main(String[] args) {
SpringApplication.run(UploaderApplication.class, args);
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/dir/**")
.addResourceLocations("file://" + workingDir)
.setCachePeriod(0);
System.out.println(workingDir);
}


But I need to give the user the ability to update the directory where the files are coming from after the app is running, since the absolute path won't always be known when the application starts. If I send a GET request from the browser with a new working directory path entered by the user, how can I update the registry?

Thank you.

Answer

This is how I decided to solve it. A user can fill out a form to update a database with the directories they will be uploading from. When the application loads it gets the list of directories and creates identifiers for them that can then be used in the html.

@SpringBootApplication
public class boxApplication extends WebMvcConfigurerAdapter {

@Autowired private TemplateRepository templateRepository;

public static void main(String[] args) {
    SpringApplication.run(boxApplication.class, args);
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {

    Template template = templateRepository.findById(1);

    for (UploadDirectory local: template.getLocalDirectories()){

        registry.addResourceHandler("/dir" + local.getId() + "/**")
                .addResourceLocations("file://" + local.getDirectory())
                .setCachePeriod(0);
    }
}
}