我正在将一个项目从Guice迁移到Dagger,并且我正在尝试理解如何在运行时注入值。假设我有一个带有以下配置方法的Guice模块:
void configure() {
install(new FactoryModuleBuilder()
.build(InterfaceXFactory.class));
}工厂接口,
public interface InterfaceXFactory{
ClassX getClassX(
@Assisted("a") String a,
@Assisted("b") Integer b);
}最后:
ClassX(
final @Assisted("a") String a,
final @Assisted("b") Integer b) {
/.../
}这种配置的等价物是什么?根据我所发现的,我可以使用AutoFactory,但我不是很好地理解它,我不知道这在Dagger中会是什么样子。也许这也不是做这件事的最佳方式。
如何将此示例转换为Dagger,以便我可以获得与Guice实现相同的功能?我真的很感谢你的帮助!
发布于 2021-06-02 02:55:24
Dagger在2.31版本中添加了自己的assisted injection,因此没有太多需要更改的地方。
工厂接口需要使用@AssistedFactory进行注释
@AssistedFactory
public interface InterfaceXFactory{
ClassX getClassX(
@Assisted("a") String a,
@Assisted("b") Integer b);
}构造函数需要使用@AssistedInject进行注释
@AssistedInject
ClassX(
final @Assisted("a") String a,
final @Assisted("b") Integer b) {
/*...*/
}不需要向模块添加任何内容;Dagger将自己找到InterfaceXFactory。
https://stackoverflow.com/questions/67793689
复制相似问题