我有一个班级,通过匕首使用DI注入。但是,当活动被销毁并重新创建时,模型类似乎自动包含数据而不会插入/重新填充数据。
public class MyApplication extends Application {
private ExpressionFactoryComponent mExpressionFactoryComponent;
@Override
public void onCreate() {
super.onCreate();
// Building dagger DI component
mExpressionFactoryComponent = DaggerExpressionFactoryComponent.builder().
expressionFactoryModule(new ExpressionFactoryModule(new ExpressionFactory(this))).build();
}
}
模块:
@Module
public class ExpressionFactoryModule {
private ExpressionFactory mExpressionFactory;
public ExpressionFactoryModule(ExpressionFactory expressionFactory) {
this.mExpressionFactory = expressionFactory;
}
@Provides
ExpressionFactory provideStringExpressionFactory() {
return mExpressionFactory;
}
}
答案 0 :(得分:1)
这样做的一个原因是ExpressionFactory
在MyApplication
类中实例化,然后在创建ExpressionFactoryModule
时传递到ExpressionFactoryComponent
的构造函数中。您应该在模块构造函数中传递Application
实例,然后使用带有@Provide
注释的metod创建类的实例,并在类的构造函数中传递Application
实例。< / p>
这应该用匕首来完成。但是要解决您的问题,您需要创建另一个组件类并在活动中构建组件,如果您需要让您的类的实例仅与活动一起生成。
这是解决方案(ExpressionFactoryComponent在这里重命名为AppComponent):
public class MyApplication extends Application {
private static AppComponent appComponent;
@Override
public void onCreate() {
super.onCreate();
// Building dagger DI component
appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this)).build();
}
public static AppComponent getAppComponent() {
return appComponent;
}
}
@Component(modules = {AppModule.class})
public interface AppComponent {
Application getApplication();
void inject(App application);
}
@Module
public class AppModule {
private Application application;
public AppModule(Application application) {
this.application = application;
}
@Provides
Application provideApplication() {
return application;
}
}
@Component(dependencies = AppComponent.class, modules = {
ActivityModule.class})
public interface ActivityComponent {
void inject(MainActivity activity);
}
@Module
public class ActivityModule {
private Activity activity;
public ActivityModule(Activity activity) {
this.activity = activity;
}
@Provides
Activity provideActivity() {
return activity;
}
@Provides
ExpressionFactory provideStringExpressionFactory(Application application) {
return new ExpressionFactory(application);
}
}
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityComponent activityComponent = DaggerActivityComponent.builder()
.activityModule(new ActivityModule(activity))
.appComponent(App.getAppComponent())
.build();
activityComponent.inject(this);
}
}