如何在Play中的静态方法中使用play.cache.CacheApi!框架2.4.2 [英] How to use the play.cache.CacheApi in a static method in Play! Framework 2.4.2

查看:386
本文介绍了如何在Play中的静态方法中使用play.cache.CacheApi!框架2.4.2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个play框架应用程序,我已经迁移到play框架2.4.2上运行。它为javascript / html前端提供RESTful API。现在我在引入缓存方面遇到了一些问题。

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.

LibraryController(将JSON / HTTP请求转换为JSON / HTTP响应):

LibraryController (transforming JSON/HTTP request to JSON/HTTP response):

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

LibraryManager(将域模型请求转换为域模型响应) :

LibraryManager (transforming domain model request to domain model response):

public class LibraryManager {

@Inject CacheApi cache;

public static Book getBook(String isbn) {

    Book book = cache.get(isbn);
    // ...
}

我在这里遇到的问题是我得

The problem I have here is that I get

non-static variable cache cannot be referenced from a static context

我注入缓存的方式是播放2.4.2缓存API文档。我根据播放2.2.x缓存API文档使用缓存时没有遇到此问题。那个版本有一个我可以调用的静态方法。

The way I am injecting the cache is as per Play 2.4.2 Cache API documentation. I didn't have this problem when I used caching as per the Play 2.2.x Cache API documentation. That version had a static method I could call.

我该怎么办?我应该使getBook非静态应用一些单例模式吗?或者我应该以其他方式访问缓存?示例代码肯定会有所帮助!

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!

推荐答案

Guice 了解 LibraryManager 使用 @Singleton 注释,从方法中删除静态关键字并将它们拉到界面:

Make Guice aware of LibraryManager using @Singleton annotation, remove static keyword from methods and pull them up to interface:

@ImplementedBy(LibraryManager.class)
public interface ILibraryManager {
    //
}

@Singleton
public class LibraryManager implements ILibraryManager {

    @Inject
    private CacheApi cache;

    @Override
    public Book getBook(String isbn) {
        Book book = cache.get(isbn);
        // ...
    }

}

现在您可以通过控制器的接口注入 LibraryManager

Now you can inject LibraryManager by an interface to your controller:

public class LibraryController extends Controller {

    @Inject
    private ILibraryManager libraryManager;

}

恭喜!你解耦 LibraryManager 并以正确的方式将其与 Play 2.4 集成。

Congratulations! You decoupled LibraryManager and integrated it with Play 2.4 in proper way.

这篇关于如何在Play中的静态方法中使用play.cache.CacheApi!框架2.4.2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆