Is it ok to bind in interface with guice? the error is No implementation for com.tobris.apps.base.service.user.UserService was bound.
UserService is an interface.
@Inject
public SyncContactService(
PartnerRepository partnerRepo,
CompanyRepository companyRepo,
CityRepository cityRepo,
CountryRepository countryRepo,
AddressRepository addressRepo,
SyncContactRepository syncContactRepo,
EmailAddressRepository emailAddressRepo,
UserService userService,
FunctionRepository functionRepo) {
this.partnerRepo = partnerRepo;
this.companyRepo = companyRepo;
this.cityRepo = cityRepo;
this.countryRepo = countryRepo;
this.addressRepo = addressRepo;
this.syncContactRepo = syncContactRepo;
this.emailAddressRepo = emailAddressRepo;
this.userService = userService;
this.functionRepo = functionRepo;
}
this is the binding code :
// bind all the web service resources
for (Class<?> type :
MetaScanner.findSubTypesOf(Object.class)
.having(Path.class)
.having(Provider.class)
.any()
.find()) {
bind(type);
}
CodePudding user response:
When you bind()
a type, you actually bind that type and not any of its interfaces. Guice works with explicit bindings, not implicit ones.
So what you should do is the following:
ScopedBindingBuilder bindAutomaticImplementation(Class<?> baseType) {
var implementations = MetaScanner.findSubTypesOf(Object.class)
.having(Path.class)
.having(Provider.class)
.any()
.find();
if (implementations.size() != 1) {
throw new RuntimeException("Too many or too few implementations for " baseType);
}
var implementation = implementation.iterator().next();
return bind(baseType.class).to(implementation);
}
Then, you have to explicitly bind the types you want:
bindAutomaticImplementation(UserService.class).in(Singleton.class);