/* * Copyright 2005-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wamblee.inject; import java.util.NoSuchElementException; import java.util.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 InjectorBuilder { private static InjectorFactory FACTORY; private static SimpleInjector INJECTOR; /** * 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. */ public static InjectorFactory getInjectorFactory() { if (FACTORY == null) { FACTORY = findInjectorFactory(); INJECTOR = new SimpleInjector(FACTORY); } return FACTORY; } /** * Gets an injector that support injection into any type of object and * performs caching of the injector obtained from the {@link InjectorFactory}. * @return Injector. */ public static Injector getInjector() { getInjectorFactory(); return INJECTOR; } /** * Finds the injector factory musing ServiceLoader * * @return InjectorFactory. */ private static InjectorFactory findInjectorFactory() { ServiceLoader factories = ServiceLoader .load(InjectorFactory.class); try { return (InjectorFactory) factories.iterator().next(); } catch (NoSuchElementException e) { throw new RuntimeException("Can not find InjectorFactory to use"); } } }