加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何使用Guice在Android Activity中注入一些接口的impl

发布时间:2020-12-15 08:45:35 所属栏目:Java 来源:网络整理
导读:我在 Android上使用Guice 3.0来做一些DI. 我有 public interface APIClient { } 和 public class DefaultAPIClient implements APIClient { } 我所做的是尝试在我的MyApplication类中引导Guice,为它提供一个模块,该模块在configure方法bind(APIClient.class)
我在 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配置错误:1)没有实现com.mycompany.APIClient绑定

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

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

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

解决方法

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

来自文档(Upgradingto20):

It’s no longer necessary/possible to inherit from RoboApplication any more since that class is gone. If you wish to override the default RoboGuice bindings,you may specify a custom module classname in a string-array resource called “roboguice_modules” in res/values/roboguice.xml. eg.

<?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应该做其余的事情.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读