X-Git-Url: http://wamblee.org/gitweb/?a=blobdiff_plain;f=support%2Finject%2Fsrc%2Fmain%2Fjava%2Forg%2Fwamblee%2Finject%2FInjectorFactoryBuilder.java;h=197311a8b262927ee39d9b45e6a9fcea79940217;hb=66baeeee93acd1da563063313179996c32bf1eaa;hp=d6005005602ff4f8e8abcf576e966966bec59919;hpb=8dff4cb222f81b1a04221fc0fa284fa5ea14d4ed;p=utils diff --git a/support/inject/src/main/java/org/wamblee/inject/InjectorFactoryBuilder.java b/support/inject/src/main/java/org/wamblee/inject/InjectorFactoryBuilder.java index d6005005..197311a8 100644 --- a/support/inject/src/main/java/org/wamblee/inject/InjectorFactoryBuilder.java +++ b/support/inject/src/main/java/org/wamblee/inject/InjectorFactoryBuilder.java @@ -19,20 +19,57 @@ import java.util.NoSuchElementException; import java.util.ServiceLoader; /** - * Utility for obtaining an implementation of the injector factory using - * {@link ServiceLoader}. + * Utility for obtaining an implementation of the {@link InjectorFactory} using + * {@link ServiceLoader} and for obtaining a {@link SimpleInjector}. + * + * The builder takes care that the factory and simple injector are built only once. + * For test code, make sure to call {@link #setInjectorFactory(InjectorFactory)} + * before each test case to force the retrieval of a new factory and injector. This + * is important because if the simple injector is not created again it will use + * cached {@link Injector} instances from other tests. * * @author Erik Brakkee */ public class InjectorFactoryBuilder { + private static InjectorFactory FACTORY; + + private static SimpleInjector INJECTOR; + /** - * Gets the injector factory by using the first one found using - * {@link ServiceLoader}. + * Sets the injector factory. This is useful for testing. + * @param aFactory Factory to use. + */ + public static void setInjectorFactory(InjectorFactory aFactory) { + FACTORY = aFactory; + INJECTOR = new SimpleInjector(aFactory); + } + + /** + * Gets the injector factory by using the first one found using + * {@link ServiceLoader}. * - * @return InjectorFactory. + * @return InjectorFactory. */ public static InjectorFactory getInjectorFactory() { + if (FACTORY == null) { + FACTORY = findInjectorFactory(); + INJECTOR = new SimpleInjector(FACTORY); + } + return FACTORY; + } + + public static SimpleInjector getInjector() { + getInjectorFactory(); + return INJECTOR; + } + + /** + * Finds the injector factory musing ServiceLoader + * + * @return InjectorFactory. + */ + private static InjectorFactory findInjectorFactory() { ServiceLoader factories = ServiceLoader .load(InjectorFactory.class); try {