Java RoboGuice:在普通类中手动注入类
我有一些接口,一些具体的类实现了这些接口。我在Java RoboGuice:在普通类中手动注入类,java,android,dependency-injection,roboguice,Java,Android,Dependency Injection,Roboguice,我有一些接口,一些具体的类实现了这些接口。我在AbstractModule类中有配置 但我的问题是:@Inject只在RoboGuice类中工作,比如RoboFragment,RoboActivity 例如: public class Fragment extends RoboFragment { @Inject ICustomClass helper; // work. helper will be initialized and call successfully. } pu
AbstractModule
类中有配置
但我的问题是:@Inject
只在RoboGuice类中工作,比如RoboFragment
,RoboActivity
例如:
public class Fragment extends RoboFragment {
@Inject
ICustomClass helper; // work. helper will be initialized and call successfully.
}
public class JavaNormalClass {
@Inject
ICustomClass helper; // doesn't work. NullPointerException
}
所以,我认为RoboGuice
在普通类中不注入自定义类,所以我应该手动调用它。(我猜!!!)那么,如何解决我的问题呢
谢谢:)这个简单的解决方案适合我 在调用任何
@Inject
成员之前,先放置这行代码。最好的方法可能是在普通类的构造函数中或在活动的创建中
public class CustomClass {
@Inject
IDBDAL dbDAL;
// can be application context or activity context
private Context mContext;
public CustomClass() {
// you can get context variable somewhere else
mContext = MyApplication.getAppContext();
RoboGuice.getInjector(mContext).injectMembersWithoutViews(this);
// from now. you can use dbDAL object
dbDAL.doSomething(); // work like charm :)
}
}
我认为这个解决方案是通用的,可以应用于多种情况。希望这有帮助:)