1 /*
2  * Copyright (C) 2014 Google, Inc.
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 dagger;
17 
18 import java.lang.annotation.Documented;
19 import java.lang.annotation.Retention;
20 import java.lang.annotation.Target;
21 import javax.inject.Inject;
22 import javax.inject.Provider;
23 import javax.inject.Qualifier;
24 import javax.inject.Scope;
25 import javax.inject.Singleton;
26 
27 import static java.lang.annotation.ElementType.TYPE;
28 import static java.lang.annotation.RetentionPolicy.RUNTIME;
29 
30 /**
31  * Annotates an interface or abstract class for which a fully-formed, dependency-injected
32  * implementation is to be generated from a set of {@linkplain #modules}. The generated class will
33  * have the name of the type annotated with {@code @Component} prepended with {@code Dagger}. For
34  * example, {@code @Component interface MyComponent {...}} will produce an implementation named
35  * {@code DaggerMyComponent}.
36  *
37  * <a name="component-methods">
38  * <h2>Component methods</h2>
39  * </a>
40  *
41  * <p>Every type annotated with {@code @Component} must contain at least one abstract component
42  * method. Component methods may have any name, but must have signatures that conform to either
43  * {@linkplain Provider provision} or {@linkplain MembersInjector members-injection} contracts.
44  *
45  * <a name="provision-methods">
46  * <h3>Provision methods</h3>
47  * </a>
48  *
49  * <p>Provision methods have no parameters and return an {@link Inject injected} or
50  * {@link Provides provided} type. Each method may have a {@link Qualifier} annotation as well. The
51  * following are all valid provision method declarations: <pre><code>
52  *   SomeType getSomeType();
53  *   {@literal Set<SomeType>} getSomeTypes();
54  *   {@literal @PortNumber} int getPortNumber();
55  * </code></pre>
56  *
57  * <p>Provision methods, like typical {@link Inject injection} sites, may use {@link Provider} or
58  * {@link Lazy} to more explicitly control provision requests. A {@link Provider} allows the user
59  * of the component to request provision any number of times by calling {@link Provider#get}. A
60  * {@link Lazy} will only ever request a single provision, but will defer it until the first call to
61  * {@link Lazy#get}. The following provision methods all request provision of the same type, but
62  * each implies different semantics: <pre><code>
63  *   SomeType getSomeType();
64  *   {@literal Provider<SomeType>} getSomeTypeProvider();
65  *   {@literal Lazy<SomeType>} getLazySomeType();
66  * </code></pre>
67  *
68  * <a name="members-injection-methods">
69  * <h3>Members-injection methods</h3>
70  * </a>
71  *
72  * <p>Members-injection methods have a single parameter and inject dependencies into each of the
73  * {@link Inject}-annotated fields and methods of the passed instance. A members-injection method
74  * may be void or return its single parameter as a convenience for chaining. The following are all
75  * valid members-injection method declarations: <pre><code>
76  *   void injectSomeType(SomeType someType);
77  *   SomeType injectAndReturnSomeType(SomeType someType);
78  * </code></pre>
79  *
80  * <p>A method with no parameters that returns a {@link MembersInjector} is equivalent to a members
81  * injection method. Calling {@link MembersInjector#injectMembers} on the returned object will
82  * perform the same work as a members injection method. For example: <pre><code>
83  *   {@literal MembersInjector<SomeType>} getSomeTypeMembersInjector();
84  * </code></pre>
85  *
86  * <h4>A note about covariance</h4>
87  *
88  * <p>While a members-injection method for a type will accept instances of its subtypes, only
89  * {@link Inject}-annotated members of the parameter type and its supertypes will be injected;
90  * members of subtypes will not. For example, given the following types, only {@code a} and
91  * {@code b} will be injected into an instance of {@code Child} when it is passed to the
92  * members-injection method {@code injectSelf(Self instance)}: <pre><code>
93  *   class Parent {
94  *     {@literal @}Inject A a;
95  *   }
96  *
97  *   class Self extends Parent {
98  *     {@literal @}Inject B b;
99  *   }
100  *
101  *   class Child extends Self {
102  *     {@literal @}Inject C c;
103  *   }
104  * </code></pre>
105  *
106  * <a name="instantiation">
107  * <h2>Instantiation</h2>
108  * </a>
109  *
110  * <p>Component implementations are primarily instantiated via a generated
111  * <a href="http://en.wikipedia.org/wiki/Builder_pattern">builder</a>. An instance of the builder
112  * is obtained using the {@code builder()} method on the component implementation.
113  * If a nested {@code @Component.Builder} type exists in the component, the {@code builder()}
114  * method will return a generated implementation of that type.  If no nested
115  * {@code @Component.Builder} exists, the returned builder has a method to set each of the
116  * {@linkplain #modules} and component {@linkplain #dependencies} named with the
117  * <a href="http://en.wikipedia.org/wiki/CamelCase">lower camel case</a> version of the module
118  * or dependency type. Each component dependency and module without a visible default constructor
119  * must be set explicitly, but any module with a default or no-args constructor accessible to the
120  * component implementation may be elided. This is an example usage of a component builder:
121  * <pre><code>
122  *   public static void main(String[] args) {
123  *     OtherComponent otherComponent = ...;
124  *     MyComponent component = DaggerMyComponent.builder()
125  *         // required because component dependencies must be set
126  *         .otherComponent(otherComponent)
127  *         // required because FlagsModule has constructor parameters
128  *         .flagsModule(new FlagsModule(args))
129  *         // may be elided because a no-args constructor is visible
130  *         .myApplicationModule(new MyApplicationModule())
131  *         .build();
132  *   }
133  * </code></pre>
134  *
135  * <p>In the case that a component has no component dependencies and only no-arg modules, the
136  * generated component will also have a factory method {@code create()}.
137  * {@code SomeComponent.create()} and {@code SomeComponent.builder().build()} are both valid and
138  * equivalent.
139  *
140  * <a name="scope">
141  * <h2>Scope</h2>
142  * </a>
143  *
144  * <p>Each Dagger component can be associated with a scope by annotating it with the
145  * {@linkplain Scope scope annotation}. The component implementation ensures that there is only one
146  * provision of each scoped binding per instance of the component. If the component declares a
147  * scope, it may only contain unscoped bindings or bindings of that scope anywhere in the graph. For
148  * example: <pre><code>
149  *   {@literal @}Singleton {@literal @}Component
150  *   interface MyApplicationComponent {
151  *     // this component can only inject types using unscoped or {@literal @}Singleton bindings
152  *   }
153  * </code></pre>
154  *
155  * <p>In order to get the proper behavior associated with a scope annotation, it is the caller's
156  * responsibility to instantiate new component instances when appropriate. A {@link Singleton}
157  * component, for instance, should only be instantiated once per application, while a
158  * {@code RequestScoped} component should be instantiated once per request. Because components are
159  * self-contained implementations, exiting a scope is as simple as dropping all references to the
160  * component instance.
161  *
162  * <a name="component-relationships">
163  * <h2>Component relationships</h2>
164  * </a>
165  *
166  * <p>While there is much utility in isolated components with purely unscoped bindings, many
167  * applications will call for multiple components with multiple scopes to interact. Dagger provides
168  * two mechanisms for relating components.
169  *
170  * <a name="subcomponents">
171  * <h3>Subcomponents</h3>
172  * </a>
173  *
174  * <p>The simplest way to relate two components is by declaring a {@link Subcomponent}. A
175  * subcomponent behaves exactly like a component, but has its implementation generated within
176  * a parent component or subcomponent. That relationship allows the subcomponent implementation to
177  * inherit the <em>entire</em> binding graph from its parent when it is declared. For that reason,
178  * a subcomponent isn't evaluated for completeness until it is associated with a parent.
179  *
180  * <p>Subcomponents are declared via a factory method on a parent component or subcomponent. The
181  * method may have any name, but must return the subcomponent. The factory method's parameters may
182  * be any number of the subcomponent's modules, but must at least include those without visible
183  * no-arg constructors. The following is an example of a factory method that creates a
184  * request-scoped subcomponent from a singleton-scoped parent: <pre><code>
185  *   {@literal @}Singleton {@literal @}Component
186  *   interface ApplicationComponent {
187  *     // component methods...
188  *
189  *     RequestComponent newRequestComponent(RequestModule requestModule);
190  *   }
191  * </code></pre>
192  *
193  * <a name="component-dependencies">
194  * <h3>Component dependencies</h3>
195  * </a>
196  *
197  * <p>While subcomponents are the simplest way to compose subgraphs of bindings, subcomponents are
198  * tightly coupled with the parents; they may use any binding defined by their ancestor component
199  * and subcomponents. As an alternative, components can use bindings only from another
200  * <em>component interface</em> by declaring a {@linkplain #dependencies component dependency}. When
201  * a type is used as a component dependency, each <a href="#provision-methods">provision method</a>
202  * on the dependency is bound as a provider. Note that <em>only</em> the bindings exposed as
203  * provision methods are available through component dependencies.
204  *
205  * @author Gregory Kick
206  * @since 2.0
207  */
208 @Retention(RUNTIME) // Allows runtimes to have specialized behavior interoperating with Dagger.
209 @Target(TYPE)
210 @Documented
211 public @interface Component {
212   /**
213    * A list of classes annotated with {@link Module} whose bindings are used to generate the
214    * component implementation. Note that through the use of {@link Module#includes} the full set of
215    * modules used to implement the component may include more modules that just those listed here.
216    */
modules()217   Class<?>[] modules() default {};
218 
219   /**
220    * A list of types that are to be used as <a href="#component-dependencies">component
221    * dependencies</a>.
222    */
dependencies()223   Class<?>[] dependencies() default {};
224 
225   /**
226    * A builder for a component. Components may have a single nested static abstract class or
227    * interface annotated with {@code @Component.Builder}.  If they do, then the component's
228    * generated builder will match the API in the type.  Builders must follow some rules:
229    * <ul>
230    * <li> A single abstract method with no arguments must exist, and must return the component.
231    *      (This is typically the {@code build()} method.)
232    * <li> All other abstract methods must take a single argument and must return void,
233    *      the Builder type, or a supertype of the builder.
234    * <li> Each component dependency <b>must</b> have an abstract setter method.
235    * <li> Each module dependency that Dagger can't instantiate itself (e.g, the module
236    *      doesn't have a visible no-args constructor) <b>must</b> have an abstract setter method.
237    *      Other module dependencies (ones that Dagger can instantiate) are allowed, but not required.
238    * <li> Non-abstract methods are allowed, but ignored as far as validation and builder generation
239    *      are concerned.
240    * </ul>
241    *
242    * For example, this could be a valid Component with a Builder: <pre><code>
243    * {@literal @}Component(modules = {BackendModule.class, FrontendModule.class})
244    * interface MyComponent {
245    *   MyWidget myWidget();
246    *
247    *   {@literal @}Component.Builder
248    *   interface Builder {
249    *     MyComponent build();
250    *     Builder backendModule(BackendModule bm);
251    *     Builder frontendModule(FrontendModule fm);
252    *   }
253    * }</code></pre>
254    */
255   @Target(TYPE)
256   @Documented
257   @interface Builder {}
258 }
259