Some concepts:

Dependency Injection (DI)

The component does not do location queries, but provides plain Java methods for the container to determine dependencies. Assembly of components for which the container is solely responsible, passing dependent objects to desired objects via JavaBean properties or constructors. Injection of dependencies through JavaBean properties is called Setter Injection; The practice of passing in dependencies as Constructor parameters is called Constructor Injection




Access mode:

The compile 'com. Google. Dagger: a dagger: 2.11' annotationProcessor 'com. Google. Dagger: a dagger - compiler: 2.11'Copy the code

Dagger2 Basic syntax:

  • @Inject
    • Use annotations to annotate other classes that depend on the target class, and also use annotations to annotate the constructors of other classes that depend on them
  • @Component

    • Associate other classes annotated (@inject) with constructors of other classes

    These are the basic accompanying annotations for Dagger2

Here’s an example:

class A{ @Inject public A{} } class B{ @Inject A a; Private public B{daggerBComponent.create ().inject(this); } } @Component interface BComponent{ inject(B b); }Copy the code

Question:

1. What is DaggerBComponent??

Dagger2 / apt (Dagger+ annotated Class name) Dagger2 / apt

2. Dependent class constructors cannot be modified. @inject cannot annotate dependent class constructors.

Dagger2 has already taken this into account, so we have to use two more annotations to solve the @Module @Provides problem

The purpose of the Module

We cannot solve the above problem by using only @inject, so how do we do it? We can encapsulate the classes of these third-party, unmodifiable constructors called Modules

  • @Module
    • The annotated Module class is actually a simple factory pattern, and the methods in the Module are basically methods that create class instances

How does @Component connect @Inject and @Module?

@Component(modules={ModuleClass.class})
interface BComponent{
   inject(B b);
}Copy the code

@Component is an injector that connects to the target class on one end and the target class dependency instance on the other. It injects the target class dependency instance into the target class. Module(modules={moduleclass.class}) is a class that provides class instances, so Module should be on the instance side of Component (the side that connects the various target class dependent instances).

How do we associate the instantiation functions of Moudle classes with the @Inject dependencies of the target class? And then we’re going to use @Provides

XXX xcannot be provided without an @provides – or @product-annotated method. XXX xcannot be provided without an @provides – or @product-annotated method.

Error XXX is bound multiple times: @provides () {error XXX is bound multiple times:

1. The constructor has basic parameters. 2. Global object transfer, how to do? Next up