【问题标题】:roboguice how to inject custom classroboguice 如何注入自定义类
【发布时间】:2013-06-23 04:00:04
【问题描述】:

嗨,我目前正在使用 roboguice 众所周知,我们可以使用注解来注入类 比如

@InjectView(R.id.list)ListView x

@inject 表示法有效,因为我从 RoboActivity 或任何 Robo 类扩展

我的问题是 如果我想注入一个自定义类,称为

public class CustomUtilManager {
}

我希望能够在 RoboActivity 中注入它

@Inject CustomUtilMananger

我该怎么做?

我的第二个问题是,如果我有一个类,那不是任何 Robo* 类的子类

public class MyOwnClass {
}

如何获取注入器并注入另一个可注入类,例如 CustomUtilManager

即怎么说呢

public class MyOwnClass {
    @Inject CustomUtilManager customUtilManager;
}

【问题讨论】:

    标签: android roboguice


    【解决方案1】:

    在 RoboActivity 中注入自定义类

    您可以简单地使用@Inject 注解注入自定义类,但注入的类必须满足以下一个条件:

    • 自定义类有一个默认构造函数(没有参数)
    • 自定义类有一个注入的构造函数。
    • 自定义类有一个 Provider 来处理实例化(更复杂)

    最简单的方法显然是使用默认构造函数。 如果您的构造函数中必须有参数,则必须将其注入:

    public class CustomClass {
    
        @Inject
        public CustomClass(Context context, Other other) {
            ...
        }
    
    }
    

    注意构造函数上的@Inject 注释。每个参数的类也必须能够被 RoboGuice 注入。 RoboGuice 开箱即用地为 Android 类提供了几个注入(例如 Context)。 Injections provided by RoboGuice

    在自定义类中注入

    如果您使用 RoboGuice 创建自定义类的实例(例如使用 @Inject 注释),所有标有 @Inject 的字段都将自动注入。

    如果你想使用new CustomClass(),你必须自己进行注入:

    public class CustomClass {
    
        @Inject
        Other other;
    
        Foo foo;
    
        public CustomClass(Context context) {
            final RoboInjector injector = RoboGuice.getInjector(context);
    
            // This will inject all fields marked with the @Inject annotation
            injector.injectMembersWithoutViews(this);
    
            // This will create an instance of Foo
            foo = injector.getInstance(Foo.class);
        }
    
    }
    

    请注意,您必须将 Context 传递给构造函数才能获取注入器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多