1

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

4

2 回答 2

2

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

RoboGuice.getInjector(context).injectMembers(this);
于 2013-01-03T12:33:50.917 回答
0

这个链接很好地解释了带有 roboguice 的单例:

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

阿童木示例

@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)];
    }
}
于 2013-12-28T11:33:42.703 回答