如何根据文档提供使用 Dagger 2 Multibinding 的 Provider

How to provide Providers using Dagger 2 Multibinding as per the documentation

参考https://dagger.dev/multibindings.html,说明

If you want a map of providers, the Map.Entry objects in your multibound set should include the providers. Then your non-multibound map can have Provider values.

我试试下面的代码。

@Module
class MyModule {
  @Provides @IntoSet
  static Map.Entry<Foo, Provider<Bar>> entry(
      Provider<Bar> barProvider) {
    Foo key = ...;
    return new SimpleImmutableEntry(key, barProvider);
  }
}

@Module
class MyProviderMapModule {
  @Provides
  static Map<Foo, Provider<Bar>> fooBarProviderMap(
      Set<Map.Entry<Foo, Provider<Bar>>> entries) {
    return ...;
  }
}

错误说明 error: [Dagger/MissingBinding] Bar cannot be provided without an @Provides-annotated method. javax.inject.Provider<Bar> is injected at MyModule.entry(barProvider) java.util.Set<java.util.Map.Entry<Foo,Provider<Bar>>> is injected at MyModule.fooBarProviderMap(entries) java.util.Map<Foo,.Provider<Bar>> is provided at MyComponent.myMapFooProviderBar()

原因是因为它不知道如何生成Provider<Bar> barProvider。所以我写下面

    @Provides
    static Provider<Bar> barProvider() {
        Provider<Bar> provider = new Provider<Bar>() {
            @Override
            public Bar get() {
                return Bar.create("1");
            }
        };
        return provider;
    }

出错了error: @Provides methods must not return framework types

我怎样才能让多重绑定示例起作用?

显然,当我们提供一个 Class 对象时,它也可以提供提供者。

@Provides
static Bar provideBar() {
    return Bar.create("xxx");
}

@Module
class MyModule {
  @Provides @IntoSet
  static Map.Entry<Foo, Provider<Bar>> entry(
      Provider<Bar> barProvider) {
    Foo key = ...;
    return new SimpleImmutableEntry(key, barProvider);
  }
}

@Module
class MyProviderMapModule {
  @Provides
  static Map<Foo, Provider<Bar>> fooBarProviderMap(
      Set<Map.Entry<Foo, Provider<Bar>>> entries) {
    return ...;
  }
}