Search code examples
javaspringrestspring-bootreturn

Perform cleanup action after return in REST method in Java Spring


I want to do cleanup of files after creating zip file. One of those action is to delete the zip file itself.

    @RequestMapping(path = "/downloadZip", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String fileName) throws IOException {

//Create a zip file and add entries

    Path path = Paths.get(file.getAbsolutePath());
    ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .body(resource);

//Call a cleanup method
//cleanUp();

}

In the Junit tests, I was able to delete the zip file using static method AfterClass .

Question: How to define a method which gets after the return.

Thanks!


Solution

  • Firstly I suggest you have a stateless web-app that doesn't need to write files. Simply use buffers instead. Especially when you say you have to clean-up the file afterwards.

    But if you can't get away with that and you still want to do tasks after you return something to the user you have a couple of options. You could use Aspects which are quiet nice so you can have a look at AspectJ. Otherwise you can also look at using Futures in conjunction with the @Async annotation on Controller methods.

    You may fine that using resources syntax as suggested in the comments will block your method returning the client's call, and you will have to make sure you handle exceptions, files not being cleaned up when some error occurs. IMO you will have some headaches down the line with this approach, such as your file-system being filled.