(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
19 /**
20  * The main entry point for programmatic dependency injection. A different
21  * {@link InjectorFactory} can be plugged in for testing.
22  * 
23  * <p>
24  * Given the following class:
25  * </p>
26  * <pre>
27  *   class Pojo {
28  *     &#064;EJB
29  *     private Service service; 
30  *   
31  *     ...
32  *   }
33  * </pre>
34  * 
35  * injecting the EJB into a POJO is accomplished as follows:
36  * 
37  * <pre>
38  * Pojo pojo = new Pojo();
39  * SimpleInjector injector = new SimpleInjector(InjectorFactoryBuilder
40  *     .getInjectorFactory());
41  * injector.inject(pojo);
42  * </pre>
43  * 
44  * Of course, the above example assumes the the injector understands the
45  * &#064;EJB annotation (which of course CDI does).
46  * 
47  * The <code>SimpleInjector</code> should be cached. This is because the
48  * <code>SimpleInjector</code> caches the {@link Injector} objects that it uses
49  * internally for performance. This is done because creation of these internal
50  * <code>Injector</code> objects may be costly. Caching the simple injector makes sure
51  * that a class is not analysed again for annotations every time injection is
52  * used.
53  * 
54  * For more advanced cases, the injector factory can also be directly
55  * constructed instead of being obtained through the
56  * {@link InjectorBuilder}.
57  * 
58  * @author Erik Brakkee
59  */
60 public class SimpleInjector implements Injector {
61
62     private InjectorCache cache;
63
64     /**
65      * Constructs the injector.
66      * 
67      * @param aFactory
68      *            Factory to use.
69      */
70     public SimpleInjector(InjectorFactory aFactory) {
71         cache = new InjectorCache(aFactory);
72     }
73
74     /**
75      * Injects into a given object.
76      * 
77      * @param aObject
78      *            Object to inject into.
79      */
80     public void inject(Object aObject) {
81         cache.getInjector(aObject.getClass()).inject(aObject);
82     }
83 }