当前位置:网站首页>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;
}
// ................
}
}
边栏推荐
- 单片机:红外遥控通信原理
- [automated test] what you need to know about unittest
- Common array methods in JS (map, filter, foreach, reduce)
- ROS topics and nodes
- Google Chrome browser reports an error: net:: err_ BLOCKED_ BY_ CLIENT
- Lambda end operation find and match allmatch
- Unity shader learning 004 shader debugging platform difference third-party debugging tools
- Single chip microcomputer: main index of a/d (analog-to-digital conversion)
- Among the four common technologies for UAV obstacle avoidance, why does Dajiang prefer binocular vision
- 【ZeloEngine】本地化流程/ImGui中文化
猜你喜欢
No more! Another member of the team left..
Redis数据持久化
Day45. data analysis practice (1): supermarket operation data analysis
Alipay native components (hotel time selection)
USB-IF BC1.2充电协议解读
Dumi construit un blog documentaire
2022 spring semester summary
Intervention analysis + pseudo regression
Line height equals height why not center
Big Five personality learning records
随机推荐
Interpretation and implementation of proxy mode
EIA map making - data processing + map making
Common array methods in JS (map, filter, foreach, reduce)
Sword finger offer 11 Minimum number of rotation array - binary lookup
Intervention analysis + pseudo regression
Real time requirements for 5g China Unicom repeater network management protocol
缓存读写--写
Single chip microcomputer: a/d differential input signal
[web] cookies and sessions
Configuration and practice of shardingsphere JDBC sub database separation of read and write
MCU: pcf8591 hardware interface
Lambda end operation find and match findfirst
Discussion sur la modélisation de la série 143
【LeetCode】860. Change with lemonade (2 brushes for wrong questions)
Data analysis report
[test development] installation of test management tool Zen path
MCU: RS485 communication and Modbus Protocol
LVS four layer load balancing cluster (3) cluster function classification - HPC
dumi 搭建文档型博客
Interpretation of usb-if bc1.2 charging protocol