DataInfoModule 中使用了@Singleton而 UserModule和MianComponent没有使用时报出的错误
.MianComponent (unscoped) may not reference scoped bindings:
@Component(modules ={UserModule.class})
^
@Provides @Singleton com.lhw.daggerdemo.bean.DataInfo com.lhw.daggerdemo.module.DataInfoModule.providerUser()
注解@Module中的includes和@Component中的modules的使用
User.java 添加多个构造函数,添加 DataInfo对象
public class User {
private DataInfo mDataInfo;
public String name;
public int age;
public String tag;
@Inject
public User() {
}
public User(DataInfo data, String tagName) {
tag = tagName;
mDataInfo = data;
}
public User(String tagName) {
tag = tagName;
}
public User(DataInfo dataInof) {
mDataInfo = dataInof;
}
DataInfo.java
public class DataInfo {
@Inject
public DataInfo(){}
public String sex;
public int height;
@Override
public String toString() {
return “DataInfo{” +
“sex='” + sex + ‘’’ +
“, height=” + height +
‘}’;
}
}
DataInfoModule.java
@Module
public class DataInfoModule {
@Provides
@Singleton
DataInfo providerUser(){
return new DataInfo();
}
}
像上面那种情况我们可以有两种处理方式
- 通过includes 引入到UserMoudle中
@Module(includes = {DataInfoModule.class}) //includes 引入moudle
public class UserModule {
@Provides @Singleton
User providerUser(){
return new User();
}
}
@Singleton
@Component(modules ={UserModule.class})
public interface MianComponent {
void inject(MainActivity