Roboguice 2.0 @将单例注入POJO

时间:2013-01-03 12:14:40

标签: android dependency-injection singleton roboguice

我创建了一个使用@Singleton注释的Settings类。这个课程已成功注入我的RoboActivities。但是当我尝试将它注入POJO(普通的旧java对象)时,我得到一个空指针异常(即未注入)。这个POJO在不同的线程中实例化(我不知道它是否相关)。最后一件事,如果我想注入该类的实例,我是否必须显式创建类的默认构造函数? 谢谢你的帮助,
托马斯

2 个答案:

答案 0 :(得分:2)

我的坏, 问题是我没有使用以下方法实例化属于另一个类的POJO:

RoboGuice.getInjector(context).injectMembers(this);

答案 1 :(得分:0)

此链接是对roboguice单身人士的一个很好的解释:

它解释了一个非常重要的警告/反模式。

Astroboy Example

@Singleton
public class Astroboy {
    // Because Astroboy is a Singleton, we can't directly inject the current Context
    // since the current context may change depending on what activity is using Astroboy
    // at the time.  Instead, inject a Provider of the current context, then we can
    // ask the provider for the context when we need it.
    // Vibrator is bound to context.getSystemService(VIBRATOR_SERVICE) in RoboModule.
    // Random has no special bindings, so Guice will create a new instance for us.
    @Inject
    Provider<Context> contextProvider;
    @Inject
    Vibrator vibrator;
    @Inject
    Random random;

    public void say(String something) {
        // Make a Toast, using the current context as returned by the Context
        // Provider
        Toast.makeText(contextProvider.get(),
                "Astroboy says, \"" + something + "\"", Toast.LENGTH_LONG)
                .show();
    }

    public void brushTeeth() {
        vibrator.vibrate(
                new long[] { 0, 200, 50, 200, 50, 200, 50, 200, 50, 200, 50,
                        200, 50, 200, 50, 200, 50, 200, 50, 200, 50, 200, 50, },
                -1);
    }

    public String punch() {
        final String expletives[] = new String[] { "POW!", "BANG!", "KERPOW!",
                "OOF!" };
        return expletives[random.nextInt(expletives.length)];
    }
}