gpt4 book ai didi

java - 游戏框架 : Access named cache in Global Settings

转载 作者:行者123 更新时间:2023-12-02 03:57:55 25 4
gpt4 key购买 nike

我正在关注文档 here并尝试在我的 play (Java) 项目中实现命名缓存。我在 Global 类中定义了一个 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
}

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

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

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

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

最佳答案

您需要使用急切的单例 - 这将允许您注入(inject)您想要的任何内容,并让它在应用程序启动时运行。

来自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");
}
}

关于java - 游戏框架 : Access named cache in Global Settings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35260253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com