roboguice how to inject custom class

2019-02-10 13:13发布

问题:

hi i am currently using roboguice as we know, we can use annotation to get class injected such as

@InjectView(R.id.list)ListView x

the @inject notation works, because i extend from RoboActivity, or any Robo class

my question is if i want to inject a custom class, called

public class CustomUtilManager {
}

i want to be able to Inject it in say RoboActivity

@Inject CustomUtilMananger

how do i do it?

my second question is, if i have a class, that is not subclass of any Robo* class

say

public class MyOwnClass {
}

how do i get the injector and inject another injectable class, such as CustomUtilManager

i.e. how can i say

public class MyOwnClass {
    @Inject CustomUtilManager customUtilManager;
}

回答1:

Injection of a custom class in RoboActivity

You can inject a custom class simply using the @Inject annotation, but the injected class must satisfy one of the following conditions:

  • The custom class have a default constructor (with no argument)
  • The custom class have one injected constructor.
  • The custom class has a Provider which handle the instantiation (more complex)

The easiest way is obviously to use a default constructor. If you must have arguments in your constructor, it must be injected :

public class CustomClass {

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

}

Notice the @Inject annotation on the constructor. The class of each argument must also be injectable by RoboGuice. Several injections for Android classes are provided out of the box by RoboGuice (for example Context). Injections provided by RoboGuice

Injection inside a custom class

If you create the instance of your custom class with RoboGuice (for example with the @Inject annotation), all the fields marked with @Inject will be injected automatically.

If you want to use new CustomClass(), you'll have to do the injection yourself:

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);
    }

}

Note that you have to pass a Context to your constructor to be able to get the injector.