3

我在 Android 上使用 Guice 3.0 来做一些 DI。

我有

public interface APIClient { }

public class DefaultAPIClient implements APIClient { }

我所做的是尝试在我的 MyApplication 类中引导 Guice,给它一个在 configure 方法中有一个语句的模块bind(APIClient.class).to(DefaultAPIClient.class);

我做了Guice例子告诉我做的事

Injector injector = Guice.createInjector(new APIClientModule());
injector.getInstance(APIClient.class);

我可能没有正确理解这一点,但我将如何将 APIClient 注入将使用它的几个活动中?

我在HomeActivity

public class HomeActivity extends RoboActivity {
    @Inject APIClient client;

    protected void onCreate(Bundle savedInstanceState) {
        client.doSomething();
    }
}

这不起作用,它给了我Guice configuration errors: 1) No implementation for com.mycompany.APIClient was bound

所以我能够让它工作的唯一方法是@Inject从 HomeActivity 中的 APIClient 客户端中删除并使用注入它client = Guice.createInjector(new APIClientModule()).getInstance(APIClient.class);

那么这是否意味着我必须在每个使用 APIClient 的 Activity 中执行此操作?我一定做错了什么。

任何帮助都会很棒。谢谢!

4

3 回答 3

4

如果您将 Roboguice 2.0 与 Guice 3.0_noaop 一起使用,定义附加自定义模块的方法是通过字符串数组资源文件 roboguice_modules:

来自文档(Upgradingto20):

由于该类已经消失,因此不再需要/不可能从 RoboApplication 继承。如果您希望覆盖默认的 RoboGuice 绑定,您可以在 res/values/roboguice.xml 中名为“roboguice_modules”的字符串数组资源中指定自定义模块类名。例如。

<?xml version="1.0" encoding="utf-8"?>
<resources> 
    <string-array name="roboguice_modules">
        <item>PACKAGE.APIClientModule</item>
    </string-array>
</resources>

因此,您需要按如下方式定义您的自定义模块:

roboguice_modules:

<?xml version="1.0" encoding="utf-8"?>
<resources> 
    <string-array name="roboguice_modules">
        <item>DONT_KNOW_YOUR_PACKAGE.APIClientModule</item>
    </string-array>
</resources>

当然,还有 APIClient 和 DefaultAPIClient 之间的绑定。

Roboguice 应该做剩下的事情。

于 2011-11-27T00:56:03.367 回答
4

非常感谢 Groupon 的 Michael Burton 在Roboguice 邮件列表上回答这个问题。对于任何感兴趣的人,这里是如何以编程方式执行此操作。

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        RoboGuice.setBaseApplicationInjector(this, RoboGuice.DEFAULT_STAGE, Modules.override(RoboGuice.newDefaultRoboModule(this)).with(new MyCustomModule()));
    }
}

现在我可以正确地注入@Inject private APIClient clientActivity。

于 2011-11-27T07:52:16.017 回答
-1

你应该使用Guice 2.0(no aop)而不是 Guice 3.0

要正确配置 Guice,您需要覆盖addApplicationModules(List<Module> modules)应用程序类中的方法并在其中添加模块。

public class MyApplication extends RoboApplication {
  @Override
  protected void addApplicationModules(List<Module> modules) {
    modules.add(new YourModule());
  }

要在您的活动中使用注入,您需要调用super.onCreate(savedInstanceState) ,因为成员是在onCreateRoboActivity 的方法中注入的。

public class HomeActivity extends RoboActivity {
    @Inject APIClient client;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); // Call this before use injected members
        client.doSomething();
    }
}
于 2011-11-26T23:55:39.737 回答