我有一个播放框架应用程序。我试图通过静态方法访问缓存。我决定将缓存包装成单例,但是当我尝试访问类CacheSingleton中的缓存变量时,我得到NullPointerException。问题怎么解决?感谢。
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){}
}
}
答案 0 :(得分:1)
不要使用静电注射。
这是不可能的"一般而言#34;: https://stackoverflow.com/a/22068572/1118419
Play使用Guice进行DI和Guice可以进行静态注射,但强烈建议不要使用此功能:
https://github.com/google/guice/wiki/Injections#static-injections
use CacheApi
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;
}
// ...
}