问题描述
让我说:
public interface Shape {}
public class Rectangle implements Shape {
}
public class Circle implements Shape {
}
,我有一个 ApplicationModule ,它需要为 Rec 和 Circle 提供实例strong>:
and I have a ApplicationModule which needs to provides instances for both Rec and Circle:
@Module
public class ApplicationModule {
private Shape rec;
private Shape circle;
public ApplicationModule() {
rec = new Rectangle();
circle= new Circle ();
}
@Provides
public Shape provideRectangle() {
return rec ;
}
@Provides
public Shape provideCircle() {
return circle;
}
}
和 ApplicationComponent :
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
Shape provideRectangle();
}
包含代码原样-无法编译。
错误说
with the code the way it is - it won't compile.error saying
这对我来说很有意义,因为该组件正试图找到 Shape
实例,它找到了其中两个,所以它不知道要返回哪个。
It makes sense to me that this can't be done, because the component is trying to find a Shape
instance, and it finds two of them, so it doesn't know which one to return.
我的问题是-我该如何处理这个问题?
My question is - how can I handle this issue?
推荐答案
我最近在这篇文章中发布了这样一个问题的答案:
I recently post the answer to a question like this in this post :
获取同一对象的多个实例您需要使用 @Named( someName)
在您的模块中像这样:
You need to use @Named("someName")
in your module like this:
@Module
public class ApplicationModule {
private Shape rec;
private Shape circle;
public ApplicationModule() {
rec = new Rectangle();
circle= new Circle ();
}
@Provides
@Named("rect")
public Shape provideRectangle() {
return rec ;
}
@Provides
@Named("circle")
public Shape provideCircle() {
return circle;
}
}
然后在任何需要注入它们的地方只要写
Then wherever you need to inject them just write
@Inject
@Named("rect")
Shape objRect;
它很有趣,但您必须以不同的方式在Kotlin中注入:
its funny but you have to inject in a different way in Kotlin:
@field:[Inject Named("rect")]
lateinit var objRect: Shape
这篇关于匕首2-两个提供相同界面的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!