Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand dagger dependency injection on Android

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

How to understand dagger dependency injection on Android, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can get something.

Brief introduction

When developing a program, a variety of objects are used, and many objects need to be initialized before they are used. For example, to manipulate a SharedPreference, you need to call getSharedPreferences (String name,int mode) to get an object before you can use it. If this object will be used in multiple Activity, you will need to write the same code in each scenario. This is not only troublesome, but also increases the possibility of making mistakes. The purpose of dagger is that you don't need to initialize objects. In other words, any object can be used directly after it is declared.

Principle

Dagger uses dependency injection, uses Annotation to mark the objects that need to be injected, and automatically injects all objects through the inject () method, thus completing the automatic initialization.

Sample code:

Public class MainActivity extends Activity {/ / Mark the object with @ Inject @ Inject SharedPreferences sharedPreferences; @ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); / / injection dependency ObjectGraph.create (AppModule.class) .inject (this) / / get the value of name and output System.out.println (sharedPreferences.getString ("name", ");}}

Dependency injection (Dependency Injection): to use a B object (dependency) in class A, you need to create a new instance of B or some other active way to obtain the object before calling it. Through the external way to automatically assign the object of B to A (injection), to achieve a relatively passive acquisition of objects, this process is called dependency injection. I'd like to know more about dependency injection being able to Google itself.

Mode of use

Take a simple boss and programmer App as an example. If you want to implement automatic injection of Boss objects, first you need to tell the program how to initialize a Boss. In dagger, add an @ Inject annotation to the constructor of the Boss class, and the program will find the marked constructor and call it when needed to get a Boss object.

Public class Boss {. @ Inject public Boss () {.}.}

It is important to note that if the constructor contains parameters, Dagger will get those parameters first when constructing the object (otherwise, who will pass the parameters? So you need to make sure that the constructors of these parameters also have the @ Inject tag, or can be obtained through the @ Provides annotation (described below).

Then, when you declare the Boss object, add the @ Inject annotation before it. The program automatically initializes the annotated object during dependency injection.

Public class MainActivity extends Activity {@ Inject Boss boss;...}

*, create the ObjectGraph class and execute the inject () method and pass in the current MainActivity as an argument, and the object of Boss is injected into the MainActivity.

Public class MainActivity extends Activity {@ Inject Boss boss; @ Override protected void onCreate (Bundle savedInstanceState) {ObjectGraph.create (AppModule.class) .inject (this);}.}

At this point, the process of injecting a Boss object into MainActivity using Dagger is complete. Two classes appear in the above code: ObjectGraph and AppModule. Which ObjectGraph is provided by Dagger class, can be simply understood as a tool class, its create function parameters for all Module, this article does not elaborate, if you are interested can follow me after the Dagger detailed explanation. AppModule is a custom class with the following code:

@ Module (injects = MainActivity.class) public class AppModule {}

As you can see, AppModule is an empty class with only one line of comments. The @ Module annotation indicates that this class is a Module,Module whose purpose is to provide information to let ObjectGraph know how to inject all dependencies. For example, the above code declares information about injectable objects: MainActivity.class (the seemingly troublesome and superfluous way of using explicit declaration is related to the principle of Dagger, which is not detailed in this article).

Custom dependency

Annotating constructors is a useful way to implement dependencies, but it is not applicable in all cases.

The interface (Interface) has no constructor

Classes provided by third-party libraries whose constructors cannot be annotated

Some classes need to be flexible in choosing the initialized configuration instead of using a single constructor

In such cases, you can use the @ Provides annotation to provide a dedicated initialization method to implement custom dependencies.

@ Provides Coder provideCoder (Boss boss) {return new Coder (boss);}

Similarly, if the @ Provides annotated method contains parameters, all of its parameters should be guaranteed to be obtained by Dagger.

All methods with @ Provides annotations need to be encapsulated in classes with @ Module annotations:

@ Module public class AppModule {@ Provides Coder provideCoder (Boss boss) {return new Coder (boss);}} singleton

Dagger supports singletons, and the implementation is very simple:

/ / @ Inject the singleton pattern of the constructor @ Singleton public class Boss {. @ Inject public Boss () {...}} ```java / / @ Provides Annotation provides the singleton pattern @ Provides @ Singleton Coder provideCoder (Boss boss) {return new Coder (boss);}

After the @ Singleton annotation is added using the above method, the object will only be initialized once, and each time thereafter will be injected directly into the same object.

Qualifier (qualifier)

If there are two types of programmers with power values of 5 and 1000 respectively, how can Dagger distinguish them? Use @ Qualifier annotations

First, create an @ interface:

@ Qualifier @ Documented @ Retention (RUNTIME) public @ interface Level {String value () default "";}

Then, set the @ Provides method for these two types of programmers and mark them differently using @ Qualifier:

@ Provides @ Level ("low") Coder provideLowLevelCoder () {Coder coder = new Coder (); coder.setName ("people with very poor fighting ability"); coder.setPower (5); return coder;} @ Provides @ Level ("high") Coder provideHighLevelCoder () {Coder coder = new Coder (); coder.setName (Great God); coder.setPower (1000); return coder;}

* use the corresponding @ Qualifier annotation when using it.

@ Inject @ Level ("low") Coder lowLevelCoder; @ Inject @ Level ("high") Coder highLevelCoder; compile time check

In essence, Dagger checks the code at compile time and reports compilation errors when the check fails (why? This has something to do with the principle of Dagger. If you are interested, you can follow the detailed explanation of Dagger released by me later. There are three main points in the inspection:

All classes that contain dependency injection need to be explicitly declared in the corresponding Module.

The parameters of all @ Provides methods in a Module must provide the corresponding @ Provides method in this Module type, or add "complete = false" after the @ Module annotation to indicate that this is an incomplete Module (that is, it will be extended by other Module).

All @ Provides methods in a Module are used by the injection object it declares, or add "library = ture" after the @ Module annotation (that is, it exists to extend other Module).

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report