title: How to use the play.cache.CacheApi in a static method in Play! Framework 2.4.2
body: <p>I have a play framework application which I have migrated to run on play framework 2.4.2. It is providing a RESTful API to a javascript/html frontend. Now I have some problems introducing caching.</p>
  
  <p>LibraryController (transforming JSON/HTTP request to JSON/HTTP response):</p>
  
  <pre><code>public class LibraryController extends Controller {
  
    public Result getBook(String isbn) {
        Book book = LibraryManager.getBook(isbn);
        BookDto bookDto = DtoMapper.book2BookDtos(book);
        return ok(Json.toJson(bookDto));
    }
  }
  </code></pre>
  
  <p>LibraryManager (transforming domain model request to domain model response):</p>
  
  <pre><code>public class LibraryManager {
  
  @Inject CacheApi cache;
  
  public static Book getBook(String isbn) {
  
      Book book = cache.get(isbn);
      // ...
  }
  </code></pre>
  
  <p>The problem I have here is that I get</p>
  
  <pre><code>non-static variable cache cannot be referenced from a static context
  </code></pre>
  
  <p>The way I am injecting the cache is as per <a href="https://www.playframework.com/documentation/2.4.x/JavaCache" rel="noreferrer">Play 2.4.2 Cache API documentation</a>. I didn't have this problem when I used caching as per the <a href="https://www.playframework.com/documentation/2.2.x/JavaCache" rel="noreferrer">Play 2.2.x Cache API documentation</a>. That version had a static method I could call.</p>
  
  <p>What should I do? Should I make getBook non-static applying some singleton pattern? Or should I access the cache in some other way? Sample code would surely help out!</p>