There are certain cases where in static attributes need to be dependency injected. Let us consider one such case. FlightUtils
is a utility class providing a static method parseDate
to parse a String in a given format and return the date. The format String is hardcoded in this API. Let us try to inject it statically.
Let us create a private static String attribute dateFormat
and create its getter and setter. Mark the setter for injection with a @Named
parameter.
@Inject public static void setDateFormat( @Named("df")String dateFormat){ FlightUtils.dateFormat = dateFormat; }
Next, prepare a module for FlightUtils
:
class FlightUtilityModule extends AbstractModule{ @Override protected void configure() { bindConstant().annotatedWith( Names.named(dateFormat)).to(dd-MM-yy); requestStaticInjection(FlightUtils.class); } }
Static injection comes into picture, (if requested) immediately once the injector instance is returned. Hence, we need not invoke the .getInstance...