我想注入一个接口并且匕首自动注入我的实现但是我得到了错误
public interface HouseInterface {
String sayHello();}
*接口的实现低于*
public class Stark implements HouseInterface{
@Inject
public Stark(){}
@Override
public String sayHello() {
return "stark";
}
}
家庭界面mosule
@Module public class HouseModule {
@Provides
public HouseInterface getHouse(Stark stark){
return stark;
}
}
* house组件:*
@Component(modules = HouseModule.class) interface HouseComponent {
HouseInterface getHouse();
}
War.class:
public class War {
@Inject
public War() {
}
//#1
//this not working
@Inject
HouseInterface houseInterface;
//this works
//#2
// @Inject
//Stark stark;
//#3
// this works//HouseComponent houseComponent = DaggerHouseComponent.builder().houseModule(new HouseModule()).build();
//HouseInterface houseInterface = houseComponent.getHouse();
public String getHouseName() {
return houseInterface.sayHello();
}
}
WarComponent类
@Component
public interface WarComponent {
War getWar();
void inject(War war);
}
当我使用以下代码测试代码时:
@Test
public void printNameTest() {
String expected = "stark";
WarComponent component = DaggerWarComponent.create();
War war= component.getWar();
Assert.assertEquals(war.getHouseName(), expected);
}
如果在War类中我们使用#1注入,而不是工作,但是如果使用#2,或者#3在上面的代码中注释注入不起作用, 谁有任何想法? 因为我不希望war.class依赖于Stark.class而我希望它只依赖于HpuseInterface所以我需要#1工作