Search code examples
propertiesdependency-injectiondagger

Dagger: Inject named string in constructor


I have a properties file and I would like to inject a property in a service.

I would like use the constructor method for DI like this:

@Inject
public ScanService(@Named("stocks.codes") String codes, IYahooService yahooService) {
    this.yahooService = yahooService;
    this.codes = codes;
}

I try to do a module like specified in this link => Dagger: Inject @Named strings?

@Provides
@Named("stocks.code")
public String providesStocksCode() {
    return "test";
}

And for the provider method for my service:

@Provides
@Singleton
public IScanService provideScanService(String codes, IYahooService yahooService){
    return new ScanService(codes, yahooService);
}

When I run the compilation I get this error:

[ERROR] /Users/stocks/src/main/java/net/modules/TestModule.java:[22,7] error: No injectable members on java.lang.String. Do you want to add an injectable constructor? required by provideScanService(java.lang.String,net.IYahooService) for net.modules.TestModule

How can I inject my property correctly in the constructor ?

Thanks.


Solution

  • You have two different names: stocks.codes and stocks.code.

    You will also have to annotate your provideScanService codes parameter:

    @Provides
    @Singleton
    public IScanService provideScanService(@Named("stocks.codes") String codes, IYahooService yahooService){
        return new ScanService(codes, yahooService);
    }
    

    Or do it like this:

    @Provides
    @Singleton
    public IScanService provideScanService(ScanService scanService){
        return scanService;
    }