Binding annotations

Sometimes we want to use numerous bindings for the same type. In our earlier example, NotificationService is bound to SMSService, which is essentially futile since the interface is bound to just one execution. If we need the client to have the adaptability to utilize any of the implementations, at that point we need to write a couple of bind statements in the configure() method, and to make that possible, we can write code as follows:

bind(NotificationService.class).annotatedWith(“sms”).to(SMSService.class);
bind(NotificationService.class).annotatedWith(“email”).to(EmailService.class);

From the previous statement, Guice knows when to bind the NotificationService interface to SMSService and when to bind it to EmailService.

The client-side code to call the SMSService implementation will look like this:

AppConsumer app = injector.getInstance(@Named("sms") AppConsumer.class);

And to call EmailService implementation:

AppConsumer app = injector.getInstance(@Named("email") AppConsumer.class);

To support such a case, binding supports non-mandatory binding annotations. A key is a pair of unique combinations of Annotation and Type. The following is the basic code to define binding annotations for SMS annotation:

@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface SMS{}

From the previous two lines, let's look at the meta-annotations:

  • @BindingAnnotation is utilized to tell Guice that this is a binding's explanation. If we ever define a different binding for the same member, then Guice may produce an error.
  • @Target and @Retention are typical annotations used to create custom annotations in Java. @Target, helps to locate field, parameter, and method, and @Ratention(RUNTIME) available in runtime respectively.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.35.122