Java – how to create an optional binding in Guice?

This is my client:

@H_ 403_ 8@

@H_ 403_ 8@

class Client {
    @Inject(optional=true) Service service;
}

Sometimes we don't need a service. We know the information when the JVM starts (that is, before the binder runs) How do I make bindings optional? If I don't specify a binding at all, it will try to create a new service (and fail because there is no zero parameter constructor: "error during package.client.service (service. Java: 40) injection: no suitable constructor can be found in package. Service."), I can't do this: @ h_403_8@

@H_ 403_ 8@

binder.bind(Service.class).toInstance(null);

Because Guice doesn't seem to allow null values Any ideas@ H_ 403_ 8@

Solution

Are you using Guice 2.0? I have tried these two. The service is an interface (the service field is always empty) and it is a class (null if it cannot create a new instance with JIT binding, and instance if it can) Both look as you expected

@H_ 403_ 8@

In both cases, I did not use the binding (service. Class) toInstance(null). If you do, you need to ensure that all injection points of the service specify that they allow it to be null This can be done by using any annotation named @ nullable (you can create it yourself or use an existing annotation) to annotate the injection point: @ h_ 403_ 8@

@H_ 403_ 8@

class Client {
    @Inject @Nullable Service service;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>