Dagger: Inject @Named strings?

后端 未结 2 1937
陌清茗
陌清茗 2020-12-03 21:09

EDIT 2018-02-08: Sample project demonstrating how to do this at https://github.com/ravn/dagger2-named-string-inject-example - Note: the whole source is in

2条回答
  •  死守一世寂寞
    2020-12-03 21:29

    You have to define a provider in the dagger module for your @Named instance.

    @Provides @Named("foo") String provideFoo()
    {
        return "foo string";
    }
    

    Then you can inject the named instance in your constructor or using field injection in your dependent class.

    public class Thermosiphon
    {
        @Inject @Named("foo") String fooString;
    
        @Inject public Thermosiphon(Heater heater)
        {
            System.out.println("value of fooString is " + fooString);
        }
    }
    

提交回复
热议问题