Static injection

Static injection is helpful when we have to migrate a static factory implementation into Guice. It makes it feasible for objects to mostly take part in dependency injection by picking up access to injected types without being injected themselves. In a module, to indicate classes to be injected on injector creation, use requestStaticInjection(). For example,  NotificationUtil is a utility class that provides a static method, timeZoneFormat, to  a string in a given format, and returns the date and timezone. The TimeZoneFormat string is hardcoded in NotificationUtil, and we will attempt to inject this utility class statically.

Consider that we have one private static string variable, timeZonFmt, with setter and getter methods. We will use @Inject for the setter injection, using the @Named parameter.

NotificationUtil will look like this:

@Inject static String timezonFmt = "yyyy-MM-dd'T'HH:mm:ss";

@Inject
public static void setTimeZoneFmt(@Named("timeZoneFmt")String timeZoneFmt){
NotificationUtil.timeZoneFormat = timeZoneFmt;
}

Now, SMSUtilModule should look like this:

class SMSUtilModule extends AbstractModule{
@Override
protected void configure() {
bindConstant().annotatedWith(Names.named(timeZoneFmt)).to(yyyy-MM-dd'T'HH:mm:ss);
requestStaticInjection(NotificationUtil.class);
}
}

 This API is not suggested for common utilization, since it faces many of the same issues as static factories. It is also difficult to test and it makes dependencies uncertain.

..................Content has been hidden....................

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