fff8f113be13fe8525e6b850366f7fac05b42589
[utils] / support / cdi / src / main / java / org / wamblee / cdi / 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.cdi;
17
18 /**
19  * Singleton injector access. This should be used as main entry point for
20  * injection. A different {@link InjectorFactory} can be plugged in for testing.
21  * 
22  * Given the following class: 
23  * <pre> 
24  * class Pojo {
25  *   &#064;EJB
26  *   private Service service; 
27  *   
28  *   ...
29  * }
30  * </pre>
31  * injecting the EJB into a POJO is accomplished as follows: 
32  * <pre>
33  *   Pojo pojo = new Pojo(); 
34  *   SimpleInjector injector = new SimpleInjector(); 
35  *   injector.inject(pojo);
36  * </pre>
37  * 
38  * Note that it is recommended to cache the injector because the injector does caching 
39  * of the types that it injects into. Caching the injector makes sure that a class is not
40  * analysed again for annotation every time injection is used. 
41  * 
42  * @author Erik Brakkee
43  */
44 public class SimpleInjector {
45
46     private InjectorCache cache = new InjectorCache(
47         new CdiInjectorFactory());
48
49     /**
50      * Constructs the injector. 
51      */
52     public SimpleInjector() { 
53         cache = new InjectorCache(new CdiInjectorFactory());
54     }
55     
56     /**
57      * Construcst the injector. 
58      * @param aFactory Factory to use. 
59      */
60     public SimpleInjector(InjectorFactory aFactory) { 
61         cache = new InjectorCache(aFactory);
62     }
63     
64     /**
65      * Injects into a given object.
66      * 
67      * @param aObject
68      *            Object to inject into.
69      */
70     public void inject(Object aObject) {
71         cache.getInjector(aObject.getClass()).inject(aObject);
72     }
73 }