Here is my client:
class Client {
@Inject(optional=true) Service service;
}
Sometimes that Service isn’t needed, and we know that information when the JVM starts (i.e before the binder is run).
How do I make the binding optional? If I don’t specify a binding at all it tries to new the Service (and fails because there is no zero-argument constructor: “Error while injecting at package.Client.service(Service.java:40): Could not find a suitable constructor in package.Service.“), and I can’t do:
binder.bind(Service.class).toInstance(null);
because Guice seems to disallow nulls. Any ideas?
Are you using Guice 2.0? I’ve tried this both with
Servicebeing an interface (service field is alwaysnull) and with it being a class (nullif it can’t create a new instance with a JIT binding, an instance if it can). Both seem like what you’d expect.In neither case did I use a binding like
bind(Service.class).toInstance(null). If you do this, then you need to make sure that all injection points forServicespecify that they allow it to benull. This can be done by annotating the injection point with any annotation called@Nullable(you can make your own or use an existing one):