mavarazy mavarazy - 9 months ago 55
Java Question

ETag support in Spring for versioned entity

I am planning to support ETag for my RESTfull Spring application. Most of the resources I expose are versioned in DB.

I am aware of ShallowEtagHeaderFilter, which is not exactly, what I need, since it only saves bandwidth.

Is there a production ready solution for Spring MVC that associates ETag header with exposed entity version?


spring-data-rest supports this out-of-the-box, see the conditional request part of the reference documentation.

You can also use Spring Framework 4.2.0+ which supports conditional requests for ResponseEntity types returned by Controller methods - see reference documentation.

Something like:

public ResponseEntity<Book> showBook(@PathVariable Long id) {

    Book book = findBook(id);
    String version = book.getVersion();

    return ResponseEntity
                .cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
                .eTag(version) // lastModified is also available