使用dagger2Dagger2子注入项目是空
修订
我有电脑和waterpump类汽车类的简单例子。我通过为什么电机中的子注入零件为空来写它们?
这是我的电机类与startEngin方法,检查计算机和waterPump启动。
public class Motor {
@Inject
public Computer computer;
@Inject
public WaterPump waterPump;
public Motor(){
}
// here computer and waterPump are null and not injected
public boolean startEngin(){
if(computer!=null && waterPump!=null){
return true;
}else{
return false;
}
}
}
,这是有型号和电压计算机类:
public class Computer {
private int vultage;
private String model;
public Computer(String model ,int vultage){
this.model=model;
this.vultage = vultage;
}
}
,这是WaterPump:
public class WaterPump {
private String name;
public WaterPump(String name){
this.name = name;
}
}
这是我的模块:
@Module
public class MotorModule {
Context context;
String motoName;
String computerName;
String waterPupName;
int voltage;
public MotorModule(Context context, String computerName, String waterPupName, int voltage) {
this.context = context;
this.waterPupName = waterPupName;
this.computerName = computerName;
this.voltage = voltage;
}
@Provides
@Singleton
Motor provideMotor() {
return new Motor();
}
@Provides
@Singleton
Computer provideComputer() {
return new Computer(computerName, voltage);
}
@Provides
@Singleton
WaterPump provideWaterPump() {
return new WaterPump(waterPupName);
}
@Provides
@Singleton
Context provideContext() {
return this.context;
}
}
这是我的组件类,我知道这一点没有必要获取Motor方法。
@Singleton
@Component(modules = {MotorModule.class})
public interface MotorComponent {
// Motor getMotor();
void inject(MainActivity activty);
,并在这里活动注入电机为空:
public class MainActivity extends AppCompatActivity {
@Inject
public Motor motor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DaggerMotorComponent.builder().motorModule(new MotorModule
(this, "mahdi'PC", "my " +
"Water pump", 12)).build().inject(this);
if (motor.startEngin()) {
Toast.makeText(this, "it is started", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "motor is not provided", Toast.LENGTH_SHORT).show();
}
}
}
}
看http://stackoverflow.com/questions/31372901/android-dagger-2-dependency-not-being-injected和变化'注入(活动活动)''来注入(MainActivity mainActivity)'。您需要指定注射部位的编译时类型 - '无效注射(活动活动)'将无法正常工作。 –
@DavidRawson OK现在汽车是不是空在您的帮助,但注射部位在汽车是零,而不是注射。 – Kenji