Reputation: 9363
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.
Upvotes: 9
Views: 11578
Reputation: 722
If you mean Dagger 2, I can help you. First you have to declare dependencies in Component
@Singleton
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
void inject(BaseActivity baseActivity);
@Named("cloud") UserDataSource userCloudSource();
@Named("disc") UserDataSource userDiscSource();
UserDataRepository userDataRepository();
}
then instantiate it in Module
@Module
public class ApplicationModule {
@Provides @Named("cloud")
UserDataSource provideCloudUserSource(UserCloudSource userSource) {
return userSource;
}
@Provides @Named("disc")
UserDataSource provideDiscUserSource(UserDiscSource userSource) {
return userSource;
}
@Provides
UserDataRepository provideUserRepository(UserDataRepository repository) {
return repository;
}
}
then inject it in constructor with @Named qualifiers
@Inject
public UserDataRepository(@Named("cloud") UserDataSource cloudSource,
@Named("disc") UserDataSource discSource) {
this.cloudDataSource= cloudSource;
this.discDataSource = discSource;
}
Upvotes: 10
Reputation: 100448
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;
}
Upvotes: 10