2 * Copyright 2005-2010 the original author or authors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.wamblee.inject;
18 import java.util.NoSuchElementException;
19 import java.util.ServiceLoader;
22 * Utility for obtaining an implementation of the {@link InjectorFactory} using
23 * {@link ServiceLoader} and for obtaining a {@link SimpleInjector}.
25 * The builder takes care that the factory and simple injector are built only once.
26 * For test code, make sure to call {@link #setInjectorFactory(InjectorFactory)}
27 * before each test case to force the retrieval of a new factory and injector. This
28 * is important because if the simple injector is not created again it will use
29 * cached {@link Injector} instances from other tests.
31 * @author Erik Brakkee
33 public class InjectorBuilder {
35 private static InjectorFactory FACTORY;
37 private static SimpleInjector INJECTOR;
40 * Sets the injector factory. This is useful for testing.
41 * @param aFactory Factory to use.
43 public static void setInjectorFactory(InjectorFactory aFactory) {
45 INJECTOR = new SimpleInjector(aFactory);
49 * Gets the injector factory by using the first one found using
50 * {@link ServiceLoader}.
52 * @return InjectorFactory.
54 public static InjectorFactory getInjectorFactory() {
55 if (FACTORY == null) {
56 FACTORY = findInjectorFactory();
57 INJECTOR = new SimpleInjector(FACTORY);
63 * Gets an injector that support injection into any type of object and
64 * performs caching of the injector obtained from the {@link InjectorFactory}.
67 public static Injector getInjector() {
73 * Finds the injector factory musing <code>ServiceLoader</code>
75 * @return InjectorFactory.
77 private static InjectorFactory findInjectorFactory() {
78 ServiceLoader<InjectorFactory> factories = ServiceLoader
79 .load(InjectorFactory.class);
81 return (InjectorFactory) factories.iterator().next();
82 } catch (NoSuchElementException e) {
83 throw new RuntimeException("Can not find InjectorFactory to use");