当前位置:网站首页>Application of dagger2 learning module (II)

Application of dagger2 learning module (II)

2022-06-13 04:15:00 rockyou666

0x00. Preface

Dagger2 Configuration and basic use of learning ( One ) The most basic Dagger2 Application .
There may be two situations in actual development , It is impossible to solve the problem by using the technical means at present .

1. Sometimes it is possible to use a third party jar package . But we can't be in a third party jar On the bag ”@Inject”
2. Constructors may need to pass in arguments .
In view of the above ”@Module” He was born .

0x01.Module Class applications

Module class :

@Module
public class ActivityModule {
    

    @Provides
    public User provideUser() {
        return new User();
    }
}

Module Class is simple to implement , Add... To the implemented entity class ”@Module” and ”@Provides”. It is essentially a factory class . This class replaces the one in the article Dagger2 Configuration and basic use of learning ( One ) In the User Class's constructor ”@Inject”, Then why use this Module Class instead ?
You must know that it is to solve the two problems at the beginning of the article . The focus of the solution is ”@Provides” And corresponding provideUser Method . such , Whether it's a third-party framework or your own code , You can put it in ”provideUser” In the middle . So what should I do if I need to pass parameters through the constructor ? Of course, there's a way , All we need to do is ”provideUser” Method uploads parameters similar to the following code :

@Provides
public User provideUser(int age) {
   return new User(age);
}

//  Or so 
@Provides
public User provideUser(int age) {
   User user = new User();
   user.setAge(age);
   return user;
}
//  This can cover all scenarios that need to pass in parameters 

Of course , If only this is not enough . Because obviously , Where are the method parameters passed in , It didn't come out of thin air .
Let's start with Component Code :

@Component
public interface ActivityComponent {
    void inject(MainActivity daggerActivity);
}

Injection into MainActivity Code for

public class MainActivity extends AppCompatActivity {
    
    // Inject 
    @Inject
    User user;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (TextView) findViewById(R.id.text);
        inject();
        Log.v("tag", "user.name::"+user.name);
    }

    // Injection behavior 
    private void inject() {
        DaggerActivityComponent.create().inject(MainActivity.this);
    }

How the parameters mentioned above are passed in ? In fact, it only needs to be transformed

DaggerActivityComponent.create().inject(MainActivity.this);

The code can be , The code is as follows :

DaggerActivityComponent.builder()
                .activityModule(new ActivityModule(23))//  Pass in the required parameters here 
                .build()
                .inject(this);

such , It completely solves the above two problems .

0x02. About Component

The last article only introduced the most basic applications , No introduction Component. So let me introduce Component.
As the previous article said .Component It can be regarded as a syringe used by doctors , It can also be seen as a connection between the injection class and the target class .

Basic usage

First, create a new java Interface , Add... To the interface @Component. Then provide an abstract method in the interface .

@Component
public interface ActivityComponent {
    void inject(MainActivity activity);
}

Of course, the above code is the simplest one .
In the use of the Module after , Need to be in @Component adopt ”modules” To indicate , Which one do you use Module.

@Component(modules = ActivityModule.class)
public interface ActivityComponent {
    void inject(MainActivity activity);
}

So you can do it Injection class and target class Build a connection . Although an interface is implemented here , But it's actually through dagger plug-in unit , Generate java Code . Part of the generated code is as follows ( The above has been annotated ):

/** *DaggerActivityComponent Realization ActivityComponent * A similar builder pattern is used here  */
@Generated("dagger.internal.codegen.ComponentProcessor")
public final class DaggerActivityComponent implements ActivityComponent {
    
  private Provider<User> provideUserProvider;
  private MembersInjector<MainActivity> mainActivityMembersInjector;

  private DaggerActivityComponent(Builder builder) {  
    assert builder != null;
    initialize(builder);
  }

  //  return Builder class 
  public static Builder builder() {  
    return new Builder();
  }

  //  initialization 
  private void initialize(final Builder builder) {  
    this.provideUserProvider = new Factory<User>() {
      private final AppComponent appComponent = builder.appComponent;
      @Override public User get() {
        User provided = appComponent.provideUser();
        if (provided == null) {
          throw new NullPointerException("Cannot return null from a [email protected] component method");
        }
        return provided;
      }
    };
    this.mainActivityMembersInjector = MainActivity_MembersInjector.create((MembersInjector) MembersInjectors.noOp(), provideUserProvider);
  }

  //  Inject 
  @Override
  public void inject(MainActivity activity) {  
    mainActivityMembersInjector.injectMembers(activity);
  }

  //  The most important Builder, Builder 
  public static final class Builder {
    
    private ActivityModule activityModule;
    private AppComponent appComponent;

    private Builder() {  
    }
    //  return ActivityComponent object .
    //  meanwhile , Pass in... In the constructor Builder object .
    public ActivityComponent build() {  
      if (activityModule == null) {
        throw new IllegalStateException("activityModule must be set");
      }
      if (appComponent == null) {
        throw new IllegalStateException("appComponent must be set");
      }
      return new DaggerActivityComponent(this);
    }
     //  Incoming ActivityModule Parameters 
    public Builder activityModule(ActivityModule activityModule) {  
      if (activityModule == null) {
        throw new NullPointerException("activityModule");
      }
      this.activityModule = activityModule;
      return this;
    }
    // ................
  }
}
原网站

版权声明
本文为[rockyou666]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/164/202206130414079028.html