xref: /aosp_15_r20/external/dagger2/java/dagger/Component.java (revision f585d8a307d0621d6060bd7e80091fdcbf94fe27)
1 /*
2  * Copyright (C) 2014 The Dagger 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 
17 package dagger;
18 
19 import static java.lang.annotation.ElementType.TYPE;
20 import static java.lang.annotation.RetentionPolicy.RUNTIME;
21 
22 import java.lang.annotation.Documented;
23 import java.lang.annotation.Retention;
24 import java.lang.annotation.Target;
25 import javax.inject.Inject;
26 import javax.inject.Provider;
27 import javax.inject.Qualifier;
28 import javax.inject.Scope;
29 import javax.inject.Singleton;
30 
31 /**
32  * Annotates an interface or abstract class for which a fully-formed, dependency-injected
33  * implementation is to be generated from a set of {@linkplain #modules}. The generated class will
34  * have the name of the type annotated with {@code @Component} prepended with {@code Dagger}. For
35  * example, {@code @Component interface MyComponent {...}} will produce an implementation named
36  * {@code DaggerMyComponent}.
37  *
38  * <p><a id="component-methods"></a>
39  *
40  * <h2>Component methods</h2>
41  *
42  * <p>Every type annotated with {@code @Component} must contain at least one abstract component
43  * method. Component methods may have any name, but must have signatures that conform to either
44  * {@linkplain Provider provision} or {@linkplain MembersInjector members-injection} contracts.
45  *
46  * <p><a id="provision-methods"></a>
47  *
48  * <h3>Provision methods</h3>
49  *
50  * <p>Provision methods have no parameters and return an {@link Inject injected} or {@link Provides
51  * provided} type. Each method may have a {@link Qualifier} annotation as well. The following are
52  * all valid provision method declarations:
53  *
54  * <pre><code>
55  *   SomeType getSomeType();
56  *   {@literal Set<SomeType>} getSomeTypes();
57  *   {@literal @PortNumber} int getPortNumber();
58  * </code></pre>
59  *
60  * <p>Provision methods, like typical {@link Inject injection} sites, may use {@link Provider} or
61  * {@link Lazy} to more explicitly control provision requests. A {@link Provider} allows the user of
62  * the component to request provision any number of times by calling {@link Provider#get}. A {@link
63  * Lazy} will only ever request a single provision, but will defer it until the first call to {@link
64  * Lazy#get}. The following provision methods all request provision of the same type, but each
65  * implies different semantics:
66  *
67  * <pre><code>
68  *   SomeType getSomeType();
69  *   {@literal Provider<SomeType>} getSomeTypeProvider();
70  *   {@literal Lazy<SomeType>} getLazySomeType();
71  * </code></pre>
72  *
73  * <a id="members-injection-methods"></a>
74  *
75  * <h3>Members-injection methods</h3>
76  *
77  * <p>Members-injection methods have a single parameter and inject dependencies into each of the
78  * {@link Inject}-annotated fields and methods of the passed instance. A members-injection method
79  * may be void or return its single parameter as a convenience for chaining. The following are all
80  * valid members-injection method declarations:
81  *
82  * <pre><code>
83  *   void injectSomeType(SomeType someType);
84  *   SomeType injectAndReturnSomeType(SomeType someType);
85  * </code></pre>
86  *
87  * <p>A method with no parameters that returns a {@link MembersInjector} is equivalent to a members
88  * injection method. Calling {@link MembersInjector#injectMembers} on the returned object will
89  * perform the same work as a members injection method. For example:
90  *
91  * <pre><code>
92  *   {@literal MembersInjector<SomeType>} getSomeTypeMembersInjector();
93  * </code></pre>
94  *
95  * <h4>A note about covariance</h4>
96  *
97  * <p>While a members-injection method for a type will accept instances of its subtypes, only {@link
98  * Inject}-annotated members of the parameter type and its supertypes will be injected; members of
99  * subtypes will not. For example, given the following types, only {@code a} and {@code b} will be
100  * injected into an instance of {@code Child} when it is passed to the members-injection method
101  * {@code injectSelf(Self instance)}:
102  *
103  * <pre><code>
104  *   class Parent {
105  *     {@literal @}Inject A a;
106  *   }
107  *
108  *   class Self extends Parent {
109  *     {@literal @}Inject B b;
110  *   }
111  *
112  *   class Child extends Self {
113  *     {@literal @}Inject C c;
114  *   }
115  * </code></pre>
116  *
117  * <a id="instantiation"></a>
118  *
119  * <h2>Instantiation</h2>
120  *
121  * <p>Component implementations are primarily instantiated via a generated <a
122  * href="http://en.wikipedia.org/wiki/Builder_pattern">builder</a> or <a
123  * href="https://en.wikipedia.org/wiki/Factory_(object-oriented_programming)">factory</a>.
124  *
125  * <p>If a nested {@link Builder @Component.Builder} or {@link Factory @Component.Factory} type
126  * exists in the component, Dagger will generate an implementation of that type. If neither exists,
127  * Dagger will generate a builder type that has a method to set each of the {@linkplain #modules}
128  * and component {@linkplain #dependencies} named with the <a
129  * href="http://en.wikipedia.org/wiki/CamelCase">lower camel case</a> version of the module or
130  * dependency type.
131  *
132  * <p>In either case, the Dagger-generated component type will have a static method, named either
133  * {@code builder()} or {@code factory()}, that returns a builder or factory instance.
134  *
135  * <p>Example of using a builder:
136  *
137  * <pre>{@code
138  * public static void main(String[] args) {
139  *   OtherComponent otherComponent = ...;
140  *   MyComponent component = DaggerMyComponent.builder()
141  *       // required because component dependencies must be set
142  *       .otherComponent(otherComponent)
143  *       // required because FlagsModule has constructor parameters
144  *       .flagsModule(new FlagsModule(args))
145  *       // may be elided because a no-args constructor is visible
146  *       .myApplicationModule(new MyApplicationModule())
147  *       .build();
148  * }
149  * }</pre>
150  *
151  * <p>Example of using a factory:
152  *
153  * <pre>{@code
154  * public static void main(String[] args) {
155  *     OtherComponent otherComponent = ...;
156  *     MyComponent component = DaggerMyComponent.factory()
157  *         .create(otherComponent, new FlagsModule(args), new MyApplicationModule());
158  *     // Note that all parameters to a factory method are required, even if one is for a module
159  *     // that Dagger could instantiate. The only case where null is legal is for a
160  *     // @BindsInstance @Nullable parameter.
161  *   }
162  * }</pre>
163  *
164  * <p>In the case that a component has no component dependencies and only no-arg modules, the
165  * generated component will also have a factory method {@code create()}. {@code
166  * SomeComponent.create()} and {@code SomeComponent.builder().build()} are both valid and
167  * equivalent.
168  *
169  * <p><a id="scope"></a>
170  *
171  * <h2>Scope</h2>
172  *
173  * <p>Each Dagger component can be associated with a scope by annotating it with the {@linkplain
174  * Scope scope annotation}. The component implementation ensures that there is only one provision of
175  * each scoped binding per instance of the component. If the component declares a scope, it may only
176  * contain unscoped bindings or bindings of that scope anywhere in the graph. For example:
177  *
178  * <pre><code>
179  *   {@literal @}Singleton {@literal @}Component
180  *   interface MyApplicationComponent {
181  *     // this component can only inject types using unscoped or {@literal @}Singleton bindings
182  *   }
183  * </code></pre>
184  *
185  * <p>In order to get the proper behavior associated with a scope annotation, it is the caller's
186  * responsibility to instantiate new component instances when appropriate. A {@link Singleton}
187  * component, for instance, should only be instantiated once per application, while a {@code
188  * RequestScoped} component should be instantiated once per request. Because components are
189  * self-contained implementations, exiting a scope is as simple as dropping all references to the
190  * component instance.
191  *
192  * <p><a id="component-relationships"></a>
193  *
194  * <h2>Component relationships</h2>
195  *
196  * <p>While there is much utility in isolated components with purely unscoped bindings, many
197  * applications will call for multiple components with multiple scopes to interact. Dagger provides
198  * two mechanisms for relating components.
199  *
200  * <p><a id="subcomponents"></a>
201  *
202  * <h3>Subcomponents</h3>
203  *
204  * <p>The simplest way to relate two components is by declaring a {@link Subcomponent}. A
205  * subcomponent behaves exactly like a component, but has its implementation generated within a
206  * parent component or subcomponent. That relationship allows the subcomponent implementation to
207  * inherit the <em>entire</em> binding graph from its parent when it is declared. For that reason, a
208  * subcomponent isn't evaluated for completeness until it is associated with a parent.
209  *
210  * <p>Subcomponents are declared by listing the class in the {@link Module#subcomponents()}
211  * attribute of one of the parent component's modules. This binds the {@link Subcomponent.Builder}
212  * or {@link Subcomponent.Factory} for that subcomponent within the parent component.
213  *
214  * <p>Subcomponents may also be declared via a factory method on a parent component or subcomponent.
215  * The method may have any name, but must return the subcomponent. The factory method's parameters
216  * may be any number of the subcomponent's modules, but must at least include those without visible
217  * no-arg constructors. The following is an example of a factory method that creates a
218  * request-scoped subcomponent from a singleton-scoped parent:
219  *
220  * <pre><code>
221  *   {@literal @}Singleton {@literal @}Component
222  *   interface ApplicationComponent {
223  *     // component methods...
224  *
225  *     RequestComponent newRequestComponent(RequestModule requestModule);
226  *   }
227  * </code></pre>
228  *
229  * <a id="component-dependencies"></a>
230  *
231  * <h3>Component dependencies</h3>
232  *
233  * <p>While subcomponents are the simplest way to compose subgraphs of bindings, subcomponents are
234  * tightly coupled with the parents; they may use any binding defined by their ancestor component
235  * and subcomponents. As an alternative, components can use bindings only from another <em>component
236  * interface</em> by declaring a {@linkplain #dependencies component dependency}. When a type is
237  * used as a component dependency, each <a href="#provision-methods">provision method</a> on the
238  * dependency is bound as a provider. Note that <em>only</em> the bindings exposed as provision
239  * methods are available through component dependencies.
240  *
241  * @since 2.0
242  */
243 @Retention(RUNTIME) // Allows runtimes to have specialized behavior interoperating with Dagger.
244 @Target(TYPE)
245 @Documented
246 public @interface Component {
247   /**
248    * A list of classes annotated with {@link Module} whose bindings are used to generate the
249    * component implementation. Note that through the use of {@link Module#includes} the full set of
250    * modules used to implement the component may include more modules that just those listed here.
251    */
modules()252   Class<?>[] modules() default {};
253 
254   /**
255    * A list of types that are to be used as <a href="#component-dependencies">component
256    * dependencies</a>.
257    */
dependencies()258   Class<?>[] dependencies() default {};
259 
260   /**
261    * A builder for a component.
262    *
263    * <p>A builder is a type with setter methods for the {@linkplain Component#modules modules},
264    * {@linkplain Component#dependencies dependencies} and {@linkplain BindsInstance bound instances}
265    * required by the component and a single no-argument build method that creates a new component
266    * instance.
267    *
268    * <p>Components may have a single nested {@code static abstract class} or {@code interface}
269    * annotated with {@code @Component.Builder}. If they do, then Dagger will generate a builder
270    * class that implements that type. Note that a component with a {@code @Component.Builder} may
271    * not also have a {@code @Component.Factory}.
272    *
273    * <p>Builder types must follow some rules:
274    *
275    * <ul>
276    *   <li>There <i>must</i> be exactly one abstract no-argument method that returns the component
277    *       type or one of its supertypes, called the "build method".
278    *   <li>There <i>may</i> be other other abstract methods, called "setter methods".
279    *   <li>Setter methods <i>must</i> take a single argument and return {@code void}, the builder
280    *       type or a supertype of the builder type.
281    *   <li>There <i>must</i> be a setter method for each {@linkplain Component#dependencies
282    *       component dependency}.
283    *   <li>There <i>must</i> be a setter method for each non-{@code abstract} {@linkplain
284    *       Component#modules module} that has non-{@code static} binding methods, unless Dagger can
285    *       instantiate that module with a visible no-argument constructor.
286    *   <li>There <i>may</i> be setter methods for modules that Dagger can instantiate or does not
287    *       need to instantiate.
288    *   <li>There <i>may</i> be setter methods annotated with {@code @BindsInstance}. These methods
289    *       bind the instance passed to them within the component. See {@link
290    *       BindsInstance @BindsInstance} for more information.
291    *   <li>There <i>may</i> be non-{@code abstract} methods, but they are ignored as far as
292    *       validation and builder generation are concerned.
293    * </ul>
294    *
295    * For example, this could be a valid {@code Component} with a {@code Builder}:
296    *
297    * <pre><code>
298    * {@literal @}Component(modules = {BackendModule.class, FrontendModule.class})
299    * interface MyComponent {
300    *   MyWidget myWidget();
301    *
302    *   {@literal @}Component.Builder
303    *   interface Builder {
304    *     Builder backendModule(BackendModule bm);
305    *     Builder frontendModule(FrontendModule fm);
306    *     {@literal @}BindsInstance
307    *     Builder foo(Foo foo);
308    *     MyComponent build();
309    *   }
310    * }</code></pre>
311    */
312   @Retention(RUNTIME) // Allows runtimes to have specialized behavior interoperating with Dagger.
313   @Target(TYPE)
314   @Documented
315   @interface Builder {}
316 
317   /**
318    * A factory for a component.
319    *
320    * <p>A factory is a type with a single method that returns a new component instance each time it
321    * is called. The parameters of that method allow the caller to provide the {@linkplain
322    * Component#modules modules}, {@linkplain Component#dependencies dependencies} and {@linkplain
323    * BindsInstance bound instances} required by the component.
324    *
325    * <p>Components may have a single nested {@code static abstract class} or {@code interface}
326    * annotated with {@code @Component.Factory}. If they do, then Dagger will generate a factory
327    * class that will implement that type. Note that a component with a {@code @Component.Factory}
328    * may not also have a {@code @Component.Builder}.
329    *
330    * <p>Factory types must follow some rules:
331    *
332    * <ul>
333    *   <li>There <i>must</i> be exactly one abstract method, which must return the component type or
334    *       one of its supertypes.
335    *   <li>The method <i>must</i> have a parameter for each {@linkplain Component#dependencies
336    *       component dependency}.
337    *   <li>The method <i>must</i> have a parameter for each non-{@code abstract} {@linkplain
338    *       Component#modules module} that has non-{@code static} binding methods, unless Dagger can
339    *       instantiate that module with a visible no-argument constructor.
340    *   <li>The method <i>may</i> have parameters for modules that Dagger can instantiate or does not
341    *       need to instantiate.
342    *   <li>The method <i>may</i> have parameters annotated with {@code @BindsInstance}. These
343    *       parameters bind the instance passed for that parameter within the component. See {@link
344    *       BindsInstance @BindsInstance} for more information.
345    *   <li>There <i>may</i> be non-{@code abstract} methods, but they are ignored as far as
346    *       validation and factory generation are concerned.
347    * </ul>
348    *
349    * For example, this could be a valid {@code Component} with a {@code Factory}:
350    *
351    * <pre><code>
352    * {@literal @}Component(modules = {BackendModule.class, FrontendModule.class})
353    * interface MyComponent {
354    *   MyWidget myWidget();
355    *
356    *   {@literal @}Component.Factory
357    *   interface Factory {
358    *     MyComponent newMyComponent(
359    *         BackendModule bm, FrontendModule fm, {@literal @}BindsInstance Foo foo);
360    *   }
361    * }</code></pre>
362    *
363    * <p>For a root component, if a {@code @Component.Factory} is defined, the generated component
364    * type will have a {@code static} method named {@code factory()} that returns an instance of that
365    * factory.
366    *
367    * @since 2.22
368    */
369   @Retention(RUNTIME) // Allows runtimes to have specialized behavior interoperating with Dagger.
370   @Target(TYPE)
371   @Documented
372   @interface Factory {}
373 }
374