我刚开始使用Dagger2,我想知道它比我目前用来实现依赖注入的技术有什么优势。
目前,为了实现DI,我创建了一个具有两种风格的项目,即mock和prod。在这些类型中,我创建了一个名为Injector的类。
//prod Injector
public class Injector {
public static INetworkLayer provideNetworkLayer() {
return new ProductionNetworkLayer();
}
}
//mock Injector
public class Injector {
public static INetworkLayer provideNetworkLayer() {
return new MockNetworkLayer();
}
}
INetworkLayer networkLayer = Injector.provideNetworkLayer();
我想知道它比我目前用来实现依赖注入的技术有什么优势。
自动依赖关系图解析,以及通过添加作用域注释确定作用域的提供程序。
但是您的示例可以很容易地转换成一个可以与Dagger2一起使用的示例,看:
//prod Injector
@Module
public class NetworkModule {
@Provides
@Singleton
public static INetworkLayer provideNetworkLayer() {
return new ProductionNetworkLayer();
}
}
//mock Injector
@Module
public class NetworkModule {
@Provides
@Singleton
public static INetworkLayer provideNetworkLayer() {
return new MockNetworkLayer();
}
}
@Singleton
@Component(modules={NetworkModule.class})
public interface SingletonComponent {
INetworkLayer provideNetworkLayer();
}
public class Injector {
private Injector() {
}
private static SingletonComponent singletonComponent;
static {
singletonComponent = DaggerSingletonComponent.create();
}
public static SingletonComponent get() {
return singletonComponent;
}
}
INetworkLayer networkLayer = Injector.get().provideNetworkLayer();
@Module
public class NetworkModule {
@Provides
@Singleton
public static INetworkLayer provideNetworkLayer(OkHttpClient okHttpClient) {
return new ProductionNetworkLayer(okHttpClient);
}
@Provides
@Singleton
public OkHttpClient provideOkHttpClient() {
return new /*create okHttpClient*/;
}
}
此外,您还可以使用@inject
注释在一定程度上简化模块。虽然在使用接口时,这一点并不明显。
@Singleton
public class ProductionNetworkLayer {
private OkHttpClient okHttpClient;
@Inject
public ProductionNetworkLayer(OkHttpClient okHttpClient) {
this.okHttpClient = okHttpClient;
}
}
@Module
public abstract class NetworkModule {
@Binds
public abstract INetworkLayer provideNetworkLayer(ProductionNetworkLayer productionNetworkLayer);
// same as `public INetworkLayer prov(ProductionNetworkLayer prod) { return prod; }`
@Provides
@Singleton
public OkHttpClient provideOkHttpClient() {
return new /*create okHttpClient*/;
}
}