Playframework:在全局设置中访问命名缓存

Playframework : Access named cache in Global Settings

我正在按照文档 here 并尝试在我的游戏 (Java) 项目中实现命名缓存。我的 Global class:

中定义了一个 beforeStart 方法,如下所示
public class Global extends GlobalSettings {
    @Inject
    @NamedCache("system-cache")
    CacheAPI cache;

    @Override
    public void beforeStart(Application app) {
    ...
    ...
    cache.set("test", "test"); //Throws a NullPointerException
}   

但是,依赖注入似乎对全局对象不起作用。我可以使用以下方式访问默认缓存:

import play.cache.Cache;
....
public class Global extends GlobalSettings {

    public void beforeStart(Application app) {
        Cache.set("test", "test"); //This works
    }
}

如何访问 GlobalSettings 中的命名缓存 class?

在 play2.4 中,GlobalSettings 发生了很多变化,您不应该使用它,并转向基于 guice 的配置,您可以在应用程序启动和停止时添加 "hooks"。

看看 here 为 java 所做的更改。
并查看 here 如何向您的应用程序添加挂钩。

您需要使用 eager singleton - 这将允许您注入任何您想要的东西,并在应用程序启动时使用它 运行。

来自documentation

GlobalSettings.beforeStart and GlobalSettings.onStart: Anything that needs to happen on start up should now be happening in the constructor of a dependency injected class. A class will perform its initialisation when the dependency injection framework loads it. If you need eager initialisation (for example, because you need to execute some code before the application is actually started), define an eager binding.

根据文档示例,您将编写一个模块来声明您的单例:

import com.google.inject.AbstractModule;
import com.google.inject.name.Names;

public class HelloModule extends AbstractModule {
    protected void configure() {

        bind(MyStartupClass.class)
                .toSelf()
                .asEagerSingleton();
    }
}

MyStartupClass 中,使用构造函数定义您的启动行为。

public class MyStartupClass {

    @Inject
    public MyStartupClass(@NamedCache("system-cache") final CacheAPI cache) {    
        cache.set("test", "test");
    }
}