(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  * The main entry point for programmatic dependency injection. A different
20  * {@link InjectorFactory} can be plugged in for testing.
21  * 
22  * <p>
23  * Given the following class:
24  * </p>
25  * 
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
51  * makes sure that a class is not analysed again for annotations every time
52  * injection is used.
53  * 
54  * For more advanced cases, the injector factory can also be directly
55  * constructed instead of being obtained through the {@link InjectorBuilder}.
56  * 
57  * @author Erik Brakkee
58  */
59 public class SimpleInjector implements Injector {
60
61     private InjectorCache cache;
62
63     /**
64      * Constructs the injector.
65      * 
66      * @param aFactory
67      *            Factory to use.
68      */
69     public SimpleInjector(InjectorFactory aFactory) {
70         cache = new InjectorCache(aFactory);
71     }
72
73     /**
74      * Injects into a given object.
75      * 
76      * @param aObject
77      *            Object to inject into.
78      */
79     public void inject(Object aObject) {
80         cache.getInjector(aObject.getClass()).inject(aObject);
81     }
82 }