Dagger injection in Base Class 是个好方法吗?
Dagger injection in Base Class is a good approach?
我有一个 Car
class 扩展 Vehicle
class,我将在车辆 class.[=23= 中注入一些属性]
示例 已编辑
abstract class Vehicle {
@Inject
lateinit var default: Default
}
class Car @Inject constructor(): Vehicle() {
}
在我的代码中一切正常,
But one thing i need to know is that how the dagger injects the
properties in base class or its hierarchy?
is this the proper way of
injecting?
谁能澄清一下?
But one thing i need to know is that how the dagger injects the properties in base class or its hierarchy?
为此,您可以查看生成的源文件。在你的情况下会有这样的事情:
class Car_Factory implements Factory<Car> {
@Override
public Car get() {
return provideInstance(
defaultProvider
);
}
public static Car provideInstance(
Provider<Default> defaultProvider
) {
Car instance = new Car();
Vehicle_MembersInjector.injectDefault(instance, defaultProvider.get()); // just instance.default = default here
return instance;
}
}
如您所见,它将创建您的实例,然后访问它的字段(只要它们 public 并且可写)。
is this the proper way of injecting?
不推荐这种方式,因为您公开的字段可能是私有的(或受保护的),并且允许外部其他人修改,这违反了封装。
因此最好以这种方式使用构造函数注入:
abstract class Vehicle(protected val default: Default)
class Car @Inject constructor(default: Default) : Vehicle(default)
通过这种方式,Dagger 将使用已经初始化的字段创建您的实例,并且不会访问它们
我有一个 Car
class 扩展 Vehicle
class,我将在车辆 class.[=23= 中注入一些属性]
示例 已编辑
abstract class Vehicle {
@Inject
lateinit var default: Default
}
class Car @Inject constructor(): Vehicle() {
}
在我的代码中一切正常,
But one thing i need to know is that how the dagger injects the properties in base class or its hierarchy?
is this the proper way of injecting?
谁能澄清一下?
But one thing i need to know is that how the dagger injects the properties in base class or its hierarchy?
为此,您可以查看生成的源文件。在你的情况下会有这样的事情:
class Car_Factory implements Factory<Car> {
@Override
public Car get() {
return provideInstance(
defaultProvider
);
}
public static Car provideInstance(
Provider<Default> defaultProvider
) {
Car instance = new Car();
Vehicle_MembersInjector.injectDefault(instance, defaultProvider.get()); // just instance.default = default here
return instance;
}
}
如您所见,它将创建您的实例,然后访问它的字段(只要它们 public 并且可写)。
is this the proper way of injecting?
不推荐这种方式,因为您公开的字段可能是私有的(或受保护的),并且允许外部其他人修改,这违反了封装。
因此最好以这种方式使用构造函数注入:
abstract class Vehicle(protected val default: Default)
class Car @Inject constructor(default: Default) : Vehicle(default)
通过这种方式,Dagger 将使用已经初始化的字段创建您的实例,并且不会访问它们