Dagger2多模块设计
问题描述:
对于Dagger2发布,我打算将模块拆分成几个小模块以供其他项目重用。Dagger2多模块设计
应用程序模块包含很多东西,我可以将它分为三种类型。 类型A相关,类型B相关,类型C相关。
所以我想把它放到三个不同的模块中,因此如果需要在其他项目上它可以重新使用它的一部分。从Google's Fork
的build.gradle的应用
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.1.0'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenCentral()
}
}
的build.gradle的应用模块
apply plugin: 'com.neenbedankt.android-apt'
//below lines go to dependenc
compile 'com.google.dagger:dagger:2.0'
apt 'com.google.dagger:dagger-compiler:2.0'
provided 'org.glassfish:javax.annotation:10.0-b28'
上述步骤后
参考,我要创造我的应用模块
@dagger.Module
public class MyApplicationModule {
void inject(MyApplication application);
}
和我的组件
@Singleton
@Component(
modules = {TypeA.class, TypeB.class, TypeC.class})
public interface MyApplicationComponent {
当我使用它的活动,它看起来像
@Component(dependencies = MyApplicationComponent.class,
modules = ActivityModule.class)
public interface ActivityComponent {
void injectActivity(SplashScreenActivity activity);
有编译问题
Error:(22, 10) error: XXXXXX cannot be provided without an @Provides- or @Produces-annotated method. com.myapplication.mXXX [injected field of type: XXX]
我想有什么不对,当我配置该Activity组件从应用程序组件扩展而来。
我的目的是应用程序组件内的一些单例对象,活动将注入同一对象以减少每次活动时创建的某个对象。 是我的设计错误?或任何其他的事情需要配置?
答
找出病根来自@Scope
必须暴露于其他子组件的使用
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface ActivityScope {
}
的类型,如果我们想要展示的应用程序的上下文,
@Singleton
@Component(
{TypeA.class, TypeB.class, TypeC.class})
public interface MyApplicationComponent {
void inject(MyApplication application);
@ForApplication
Context appContext();
当我的子组件想要扩展这个
@ActivityScope
@Component(dependencies = MyApplicationComponent.class,
modules = ActivityModule.class)
public interface ActivityComponent extends MyApplicationComponent {
void injectActivity(Activity activity);
我认为这对于Dagger2是一件好事,让你手动暴露你需要使用的对象,代码变得更加可追踪。