(no commit message)
[utils] / support / inject / src / main / java / org / wamblee / inject / SimpleInjector.java
1 /*
2  * Copyright 2005-2010 the original author or authors.
3  * 
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
7  * 
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  * 
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.
15  */
16 package org.wamblee.inject;
17
18 import java.util.ServiceLoader;
19
20
21 /**
22  * Singleton injector access. This should be used as main entry point for
23  * injection. A different {@link InjectorFactory} can be plugged in for testing.
24  * 
25  * Given the following class: 
26  * <pre> 
27  * class Pojo {
28  *   &#064;EJB
29  *   private Service service; 
30  *   
31  *   ...
32  * }
33  * </pre>
34  * injecting the EJB into a POJO using Contexts and Dependency Injection is accomplished as follows: 
35  * <pre>
36  *   Pojo pojo = new Pojo(); 
37  *   SimpleInjector injector = new SimpleInjector(new CdiInjectorFactory()); 
38  *   injector.inject(pojo);
39  * </pre>
40  * 
41  * Note that it is recommended to cache the injector because the injector does caching 
42  * of the types that it injects into. Caching the injector makes sure that a class is not
43  * analysed again for annotation every time injection is used. 
44  * 
45  * The {@link InjectorFactory} to be used can also be found using a {@link ServiceLoader} discovery
46  * mechanism as provided by {@link InjectorFactoryBuilder}. 
47  * 
48  * @author Erik Brakkee
49  */
50 public class SimpleInjector {
51
52     private InjectorCache cache;
53
54     /**
55      * Constructs the injector. 
56      * @param aFactory Factory to use. 
57      */
58     public SimpleInjector(InjectorFactory aFactory) { 
59         cache = new InjectorCache(aFactory);
60     }
61     
62     /**
63      * Injects into a given object.
64      * 
65      * @param aObject
66      *            Object to inject into.
67      */
68     public void inject(Object aObject) {
69         cache.getInjector(aObject.getClass()).inject(aObject);
70     }
71 }