This article has been authorized by the public number Guolin_blog (Guo Lin) exclusive release
MVP Mode Explanation
Using Dagger2 in MVP
Analysis of injection principle of Dagger2
In the previous blog we introduced Dagger2 how to use in the project, this blog will continue to analyze the principle of Dagger2 implementation, the code is still using the previous code, see here.
The injection principle of Dagger2
The explanation of the principle we learn through Ming Li.
Xiao Ming saw the MVP of the actual combat analysis and the use of Dagger2 know how to use the MVP model, but Xiao Ming is a good classmate of the request, Xiao Ming is not satisfied with how to use, Xiao Ming want to delve into the source, see how to achieve.
Xiao Ming in the study of Dagger2 suddenly realized that Dagger2 is to use the form of annotations to complete the task, using annotations is actually unwise choice, will greatly consume performance, affect the speed of application. Xiao Ming saw here a little puzzled, since the annotations so affect performance, then why Dagger2 also use annotations? Why is Dagger2 so widely used?
So Xiaoming went to GitHub to see Dagger2 's introduction
Official introduction is
A Fast Dependency injector for Android and Java.
Dagger2 is a quick syringe in Android and Java.
Xiaoming again puzzled how is the annotation reflection fast?
Xiao Ming did not lose heart and continue to look at the code, and finally found that Dagger2 is different from other dependency injection framework, Dagger2 is through the apt plugin to generate injected code during the compilation phase, that is, reflection is only used in the compilation phase, While the application is running when the actual Java code is running is not related to annotation reflection, Xiaoming finally understand, no wonder Dagger2 is fast injection framework.
Xiao Ming had this big discovery and decided to bang the code generated by Dagger2 to clarify.
Generate code in the compile phase
By executing Build->rebuild Project in Android studio, Xiaoming found a build in the APP/BUILD/GENERATED/SOURCE/APT directory
Loginpresentercomp_factory class
The code is as follows
Public Final class loginpresentercompl_factory implements Factory< Loginpresentercompl> { Private FinalProvider<iloginview> Viewprovider; PublicLoginpresentercompl_factory (provider<iloginview> viewprovider) {assert Viewprovider! =NULL; This. Viewprovider = Viewprovider; } @Override PublicLoginpresentercompl get () {return NewLoginpresentercompl (Viewprovider.get ()); } Public StaticFactory<loginpresentercompl> Create (provider<iloginview> viewprovider) {return NewLoginpresentercompl_factory (Viewprovider); }}
To find out about Bi Xiaoming and Loginpresentercompl's code.
The code is as follows
publicclass LoginPresenterCompl implements ILoginPresenter { @Inject publicLoginPresenterCompl(ILoginView view){ loginView = view ; new User("张三","123456") ; } ......}
Take a closer look at the Loginpresentercompl_factory class and discover that there are three ways
The parameters in the constructor viewprovider a provider type, and provider's generic parameter is Iloginview, which is the parameter we need to instantiate Loginpresentercompl, In the previous article we learned that this parameter is a dependency and is provided by Mainmodule.
In this method, we initialize the Loginpresentercompl object we are going to need.
The Loginpresentercompl_factory class object is instantiated in this method.
Xiao Ming think since the above viewprovider is provided by Mainmodule, then take a look at Mainmodule corresponding injection class bar
Mainmodule_provideilogviewfactory
The code is as follows
Public Final class mainmodule_provideilogviewfactory implements Factory< Iloginview> { Private FinalMainmodule module; PublicMainmodule_provideilogviewfactory (Mainmodule module) {Assert module! =NULL; This. module = module; } @Override PublicIloginview get () {returnPreconditions.checknotnull (Module.provideilogview (),"cannot return null from a [email protected] @Provides method"); } Public StaticFactory<iloginview> Create (Mainmodule module) {return NewMainmodule_provideilogviewfactory (module); }}
The corresponding Mainmodule code is as follows
@Modulepublicclass MainModule { privatefinal ILoginView view ; publicMainModule(ILoginView view){ this.view = view ; } @Provides ILoginView provideILogView(){ return view ; }}
It is not difficult to see from the structure of the @provider annotation modified method will correspond to generate factory class, the most important method of this class is the Get () method, in which the Mainmodule Provideilogview method is called, And the method is for us to provide Loginpresentercompl instantiation parameters, Loginpresentercompl instantiation is done in the Loginpresentercompl_factory get () method.
The instantiation code is as follows
@Overridepublicget() { returnnew LoginPresenterCompl(viewProvider.get());}
You can see in the code that the parameters are provided by Viewprovider.get () during instantiation. Hey!!!!
The Get () method in Mainmodule_provideilogviewfactory actually returns the arguments that we instantiated.
So is this viewprovider our mainmodule_provideilogviewfactory?
Viewprovider is a provider type, and Mainmodule_provideilogviewfactory implements the factory interface, that provider and factory have no connection?
Look at this piece of code.
publicinterface Factory<T> extends Provider<T> {}
The factory interface is found to inherit the provider interface, so Viewprovider is actually the mainmodule_provideilogviewfactory type.
See here Xiao Ming finally understand the Loginpresentercompl_factory class and Mainmodule_provideiloginviewfactory class relationship, also understand the instantiation of the process.
But how are the initialization and related methods of these classes called, and where are they called?
There are two important classes that xiaoming did not see. Maincomponent and the corresponding daggermaincomponent.
The code is as follows
Maincomponent Code
@Component(modules = MainModule.class)publicinterface MainComponent { publicvoidinject(LoginActivity activity) ;}
Daggermaincomponent Code
Public Final class daggermaincomponent implements maincomponent { PrivateProvider<iloginview> Provideilogviewprovider;PrivateProvider<loginpresentercompl> Loginpresentercomplprovider;PrivateMembersinjector<loginactivity> Loginactivitymembersinjector;Private daggermaincomponent(Builder builder) {assertBuilder! =NULL; Initialize (builder); } Public StaticBuilderBuilder() {return NewBuilder (); }@SuppressWarnings("Unchecked")Private void Initialize(FinalBuilder builder) { This. Provideilogviewprovider = Mainmodule_provideilogviewfactory.create (builder.mainmodule); This. Loginpresentercomplprovider = Loginpresentercompl_factory.create (Provideilogviewprovider); This. Loginactivitymembersinjector = Loginactivity_membersinjector.create (Loginpresentercomplprovider); }@Override Public void Inject(loginactivity activity) {loginactivitymembersinjector.injectmembers (activity); } Public Static Final class Builder { PrivateMainmodule Mainmodule;Private Builder() {} PublicMaincomponentBuild() {if(Mainmodule = =NULL) {Throw NewIllegalStateException (MainModule.class.getCanonicalName () +"must be set"); }return NewDaggermaincomponent ( This); } PublicBuilderMainmodule(Mainmodule mainmodule) { This. Mainmodule = Preconditions.checknotnull (mainmodule);return This; } }}
It can be seen from the above code that daggermaincomponent implements the Maincomponent interface and implements the inject () method. Other auxiliary methods are also available.
Xiaoming decided to start with the method invocation order to see
DaggerMainComponent.builder().mainModule(new MainModule(this)).build().inject(this);
Injection process
Remember the method you added in Loginactivity, analyze daggermaincomponent and start with this code.
- 1, Daggermaincomponent called the Builder method
Xiao Ming found the Builder () method to see what the method actually did.
publicstaticbuilder() { returnnew Builder();}
Found this method to create and return the builder object
What is Builder? A closer look at code build is the inner class of Daggermaincompone.
- 2, Daggermaincomponent.builder (). Mainmodule (New Mainmodule (This))
The mainmodule is then called and the Mainmodule object is passed in.
The Mainmodule () method is a method in builder, and the code is as follows
publicmainModule(MainModule mainModule) { this.mainModule = Preconditions.checkNotNull(mainModule); returnthis;}
What did it do? is to assign the passed-in Mainmodule object to the Mainmodule object of this class and return the object of this class
- 3, Daggermaincomponent.builder (). Mainmodule (New Mainmodule (this)). Build ()
The builder's Build () method is then called
publicbuild() { ifnull) { thrownew" must be set"); } returnnew DaggerMainComponent(this);}
The method creates a Daggermaincomponent object with new Daggermaincomponent (this) and returns it.
So what does new daggermaincomponent (this) do?
privateDaggerMainComponent(Builder builder) { assertnull; initialize(builder);}
Where the Initialize method is called and the Builder object is passed in.
The Initialize () method is as follows
privatevoidinitialize(final Builder builder) { this.provideILogViewProvider = MainModule_ProvideILogViewFactory.create(builder.mainModule); this.loginPresenterComplProvider = LoginPresenterCompl_Factory.create(provideILogViewProvider); this.loginActivityMembersInjector = LoginActivity_MembersInjector.create(loginPresenterComplProvider);}
In the Initialize method, Xiaoming finally saw the Mainmodule_provideilogviewfactory and loginpresentercompl_factory the Create method was called.
The Mainmodule_provideilogviewfactory object is created first through the incoming Mainmodule object
Provideilogviewprovider, and then creates the Provideilogviewprovider object as a parameter
The Loginpresentercompl_factory object.
As has been said before, Mainmodule_provideilogviewfactory is a factory object,
Loginpresentercompl_factory creates an object that requires a provider object, and factory inherits provider, so it can be passed in.
So Loginpresentercomp_factory's Viewprovider object
is a Mainmodule_provideilogviewfactory object,
This concept has been mentioned before and is certified here.
In this code, Xiao Ming found the Loginactivity_membersinjector class, so Xiao Ming again to find out the class
The code is as follows
PublicFinalclassLoginactivity_membersinjector implements Membersinjector<loginactivity> {PrivateFinal provider<loginpresentercompl> Loginpresenterprovider; Public Loginactivity_membersinjector(provider<loginpresentercompl> Loginpresenterprovider) {Assert Loginpresenterprovider! =NULL; This. Loginpresenterprovider = Loginpresenterprovider; } Public StaticMembersinjector<loginactivity>Create(provider<loginpresentercompl> Loginpresenterprovider) {return NewLoginactivity_membersinjector (Loginpresenterprovider); } @Override Public void injectmembers(loginactivity instance) {if(Instance = =NULL) {Throw NewNullPointerException ("cannot inject" into a null reference "); } Instance.loginpresenter = Loginpresenterprovider.Get(); } Public Static void Injectloginpresenter(loginactivity instance, provider<loginpresentercompl> loginpresenterprovider) {instance.loginpresenter = Loginpresenterprovider.Get(); }}
The Cereate () method of the class requires that a provider generic be a parameter of type Loginpresentercompl that is passed through the constructor to the Loginpresenterprovider variable. It's so simple.
- 4, Daggermaincomponent.builder (). Mainmodule (New Mainmodule (this)). Build (). Inject (This)
Finally, the inject () method is called
@Overridepublicvoidinject(LoginActivity activity) { loginActivityMembersInjector.injectMembers(activity);}
The Injectmembers () method in Loginactivitymembersinjector is called in this method.
Injectmembers () method content is as follows
@OverridepublicvoidinjectMembers(LoginActivity instance) { ifnull) { thrownew NullPointerException("Cannot inject members into a null reference"); } instance.loginPresenter = loginPresenterProvider.get();}
Finally!!!!!!! The initialization of the Loginpresentercompl object is implemented in this method.
At this point, Xiaoming finally can clear the Dagger2 injection principle, Xiao Ming said clear principle after mother no longer have to worry about Dagger2 write wrong.
If there is no correct analysis of the generated injection class may be difficult to understand the DAGGER2 implementation of the framework of the injection, may see the principle of code to let some students at a loss, believe me, more analysis several times OK.
In fact, there is no need to tangle in the end how to use Dagger2, as long as we understand the principle of its implementation, specific how to use to see the individual, can do flexible use on OK.
At this point Dagger2 's analysis of the principle is completed.
Summarize
Review the articles in this series
MVP Mode Explanation
Using Dagger2 in MVP
Analysis of injection principle of Dagger2
Since these three articles are sequential, the code is expanded on the basis of the previous article, so it's best to read through three blogs.
Hope that these three articles can help the needs of students, common progress!!!
Last all code click here
Dagger2 injection principle analysis of King series on Android single row