首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >播放框架CacheApi注入返回单酮中的NullPointeerException

播放框架CacheApi注入返回单酮中的NullPointeerException
EN

Stack Overflow用户
提问于 2017-02-15 13:09:35
回答 1查看 311关注 0票数 1

我有一个游戏框架应用程序。我试图通过静态方法访问缓存。我决定将缓存包装到单例中,但是当尝试访问类NullPointerException中的缓存变量时,我得到了CacheSingleton。如何解决这个问题?谢谢。

代码语言:javascript
复制
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){}
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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的正确方法

代码语言:javascript
复制
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;
    }

    // ...
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42250330

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档