3. Dagger2: Implementation of Component, dagger2component
Translation
Mark an interface or abstract classThe modules set generates a complete implementation of dependency injection. The generated class will@ Component: Class Name and Dagger prefix name. For example{@ Code @ Component interface MyComponent {...} will generateDaggerMyComponent implementation.
1. Component-methods (Component-method)
Every use@ Component the annotation type must contain at least one AbstractComponent method.The Component method has any name, but must complyProvision orMerbers-injection format signature.
1.1 Provision methods (provides class methods)
The Provision method has no parameters and returnsInjected orProvided type. Each method may have a limited annotation. The following are all validProvision Method declaration:
SomeType getSomeType(); Set getSomeTypes(); @PortNumber int getPortNumber();
Provision method, such as a typicalInjection Location, which can be usedProvider orLazy more explicit controlProvision request. OneProvider allowedThe component User passesProvider. get () pairProvision executes any number of requests.Lazy will only request a separateProvision, but it will be delayed until the first callLazy. get. The followingThe provision method requests the same type.Provision, but each has different semantics:
SomeType getSomeType(); Provider getSomeTypeProvider(); Lazy getLazySomeType();
1.2 Members-injection methods (member injection method)
The Members-injection method has a separate parameter, which injects dependencies into each of the parameter instances.@ Inject member variables and methods. The returned value of the member injection method may be void or a unique parameter to facilitate chained call. The following is a valid member injection method statement:
void injectSomeType(SomeType someType); SomeType injectAndReturnSomeType(SomeType someType);
A return with no parametersThe MembersInjector method is equivalent to a member injection method. Call on the returned objectMemberInjector. injectMembers has the same effect as a member injection method, for example:
MembersInjector getSomeTypeMembersInjector();
1.3 A note about covariance (I don't know how to translate, "A knowledge point related to covariance "?)
AlthoughThe members-injection method can receive its child-type instances, but only@ Inject member variables can be injected. The sub-type member variables do not work. For example, given the following types, whenChild instance passed inMember-injection MethodIn injectSelf (Self instance), onlyA andB can be injected into the Child instance.
class Parent { @Inject A a; } class Self extends Parent { @Inject B b; } class Child extends Self { @Inject C c; }
2. Instantiation (Instantiation)
The Component implementation example is mainly through generated)Builder instantiated.Builder instancesComponent'sBuilder () method. IfA@ Component. Builder type,The builder () method returns a generated implementation example of this type. If no embedded@ Component. Builder, returnBuilder SetsModule and dependency typeModules andComponent dependency. For each non-visible default constructorComponent dependency andThe module must be explicitly set, but any constructor with the default or no parameters andTheComponent dependency andThe module can be omitted. Below isExample of using component builder:
public static void main(String[] args) { OtherComponent otherComponent = ...; MyComponent component = DaggerMyComponent.builder() // required because component dependencies must be set .otherComponent(otherComponent) // required because FlagsModule has constructor parameters .flagsModule(new FlagsModule(args)) // may be elided because a no-args constructor is visible .myApplicationModule(new MyApplicationModule()) .build(); }
In this example,Component does notComponent dependency and only has no parametersModules, the generatedComponent also has a factory MethodCreate ().SomeComponent. create () andSomeComponent. builder (). build () is both effective and equivalent.
3. Scope)
Each DaggerComponent usageScope annotation can be associated with oneScope.Component implementation ensures thatScoped binding,Only one of the component instancesProvision. IfComponent declaresScope, which only containsUnscoped bindings orScopeBindings, such
@Singleton @Component interface MyApplicationComponent { // this component can only inject types using unscoped or @Singleton bindings }
To obtainScope annotation related appropriate behavior, the caller is responsible for creating at the appropriate timeComponent instance. For exampleComponent can only be instantiated once in an application, whileRequestedScopedComponent needs to be instantiated every request. BecauseComponent is a self-contained implementation and hasScope is like throwing all referencesThe component instance is just as simple.
4. Component relationships (Component relationship)
Although simpleUnscoped bindingsComponent has a lot of use, and many applications still have manyScopes manyComponent interaction requirements. Dagger provides (below) two mechanisms to associate Components.
4.1 Subcomponents)
Associate twoThe simplest way for components is to declareSubcomponent.Subcomponent acts likeComponent, but at the upper level (parent)Component orSubcomponent internally generates its implementation. This relationship allowsWhen the subcomponent is declared, its implementation inherits itsAll of the parentBinding diagram. For this reasonWhen it is associatedParent is incomplete.
By addingSubcomponent class included in parentOne of componentModuleSubcomponents () attribute DeclarationSubcomponent. SoBound to the parent componentSubcomponent.Builder
Subcomponents can also be passed throughParent component orFactory method declaration on subcomponent. The method name is arbitrary, butThe parameter of the subcomponent. Factory method can beAny number of subcomponentModules, but at least must containModule. The following is an example of a factory method.Singleton-scopedparent createsrequest-scoped subcomponent:
@Singleton @Component interface ApplicationComponent { // component methods... RequestComponent newRequestComponent(RequestModule requestModule); }
4.2 Component dependencies (Component dependency)
AlthoughSubcomponents is composedBindings subgraphs are the simplest method,Subcomponents andParent is very tightly integrated; they can use any of their ancestor level (ancestor)Component andThe binding. defined by subcomponents can be declaredComponent dependency,Components can only useTheBindings. When a type is usedComponent dependency, which depends on each of the aboveThe provision method is bound toProvider. Note thatComponent dependency, only exposedProvision MethodBindings is valid.