Following the documentation of OptionalBinder
An API to bind optional values, optionally with a default value. OptionalBinder fulfills two roles:
- It allows a framework to define an injection point that may or may not be bound by users.
- It allows a framework to supply a default value that can be changed by users.
I am trying to follow up on the first point above for which I have the following setup:
interface Reporting<R> {} // service to be bind optionally
class InternalServiceImpl implements InternalService {
@Inject
Reporting reporting;
... // use this in a method
}
public class FrameworkModule extends AbstractModule {
protected void configure() {
OptionalBinder.newOptionalBinder(binder(), Reporting.class);
}
}
in the user modules(class UserWorkingModule) if I do not provide a binding such as
bind(new TypeLiteral<Reporting<ReportingEvent>>(){}).to(ReportingImpl.class).in(Singleton.class);
the application fails to start with the following logs:
1) No implementation for Reporting was bound. while locating Reporting for field at InternalServiceImpl.reporting(InternalServiceImpl.java:21) at FrameworkModule.configure(FrameworkModule.java:55) (via modules: UserWorkingModule -> FrameworkModule)
Is it still a must to provide a binding for Reporting in the UserWorkingModule?
is a binding for the generic
Reporting<ReportingEvent>, whileis actually specifying the raw type,
Reporting. Instead, you want to use the overload fornewOptionalBinderwhich specifies a TypeLiteral arg, so that you are talking about the same thing in both the optional request and the binding:Without this, you are basically saying "any binding to Reporting will satisfy this requirement", even something like
Reporting<Object>- and what happens if you bind more than one?On the other hand, if you actually want to allow any binding of any
Reportingtype (which is what your error suggests, then instead the opposite thing is wrong: instead of binding to rawReporting, you specified the generic impl instead. Change that bind() call to say "this actually only works for raw requests":