匕首:在构造函数中注入命名字符串

Dagger: Inject named string in constructor

我有一个属性文件,我想在服务中注入一个属性。

我想像这样使用 DI 的构造函数方法:

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

我试着做一个像这个link => Dagger: Inject @Named strings?

中指定的模块
@Provides
@Named("stocks.code")
public String providesStocksCode() {
    return "test";
}

对于我的服务的提供者方法:

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

当我运行编译时出现这个错误:

[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

如何在构造函数中正确注入我的属性?

谢谢。

您有两个不同的名字:stocks.codesstocks.code

您还必须注释您的 provideScanService codes 参数:

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

或者这样做:

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

如果你说的是匕首2,我可以帮你。 首先你必须在 Component

中声明依赖
@Singleton
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
    void inject(BaseActivity baseActivity);

    @Named("cloud") UserDataSource userCloudSource();
    @Named("disc") UserDataSource userDiscSource(); 
    UserDataRepository userDataRepository();  
}

然后在模块

中实例化它
@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;
    }

}

然后用@Named限定符将它注入到构造函数中

@Inject
public UserDataRepository(@Named("cloud") UserDataSource cloudSource, 
     @Named("disc") UserDataSource discSource) {
    this.cloudDataSource= cloudSource;
    this.discDataSource = discSource;
}