我有一个游戏框架应用程序。我试图通过静态方法访问缓存。我决定将缓存包装到单例中,但是当尝试访问类NullPointerException中的缓存变量时,我得到了CacheSingleton。如何解决这个问题?谢谢。
import javax.inject.*;
import play.cache.*;
@Singleton
public final class CacheSingleton {
@Inject CacheApi cache;
private static volatile CacheSingleton instance = null;
private CacheSingleton() {
}
public static CacheSingleton getInstance() {
if (instance == null) {
synchronized(CacheSingleton.class) {
if (instance == null) {
instance = new CacheSingleton();
}
}
}
return instance;
}
}
public class CustomLabels {
public static String get() {
CacheSingleton tmp = CacheSingleton.getInstance();
try
{
tmp.cache.set("key", "value");
}catch(Exception e){}
}
}发布于 2017-02-16 08:12:46
不使用静态注入.
“总体上”是不可能的:https://stackoverflow.com/a/22068572/1118419
Play use Guice for DI和Guice可以进行静态注入,但强烈建议不要使用此功能:
https://github.com/google/guice/wiki/Injections#static-injections
实现 in Play的正确方法
import play.cache.*;
import play.mvc.*;
import javax.inject.Inject;
public class Application extends Controller {
private CacheApi cache;
@Inject
public Application(CacheApi cache) {
this.cache = cache;
}
// ...
}https://stackoverflow.com/questions/42250330
复制相似问题