当前位置:网站首页>Arouter source code analysis (III)
Arouter source code analysis (III)
2022-07-28 09:40:00 【Yu Qirong】
arouter-api version : 1.4.1
Preface
Up to now ,ARouter And the last dependency injection has not been resolved , So today, let's explore its implementation principle .
PS : Because the principle of dependency injection is relatively simple , So this article will be short .
@Autowired analysis
Want to use ARouter Implement dependency injection , Need to be in Activity/Fragment Medium plus
ARouter.getInstance().inject(this);Then our code becomes the entry point for our analysis .
public void inject(Object thiz) {
_ARouter.inject(thiz);
}ARouter It's called internally _ARouter Of inject Method .
static void inject(Object thiz) {
AutowiredService autowiredService = ((AutowiredService) ARouter.getInstance().build("/arouter/service/autowired").navigation());
// If autowiredService Not empty , Complete dependency injection
if (null != autowiredService) {
autowiredService.autowire(thiz);
}
}It is found that dependency injection is very similar to interceptors , It is all done by using service components . The service component of dependency injection is called AutowiredService , Tracking can find , Its implementation class is AutowiredServiceImpl .
@Route(path = "/arouter/service/autowired")
public class AutowiredServiceImpl implements AutowiredService {
private LruCache<String, ISyringe> classCache;
private List<String> blackList;
@Override
public void init(Context context) {
classCache = new LruCache<>(66);
blackList = new ArrayList<>();
}
@Override
public void autowire(Object instance) {
String className = instance.getClass().getName();
try {
// If instance This class is on the blacklist , Dependency injection will not be completed
if (!blackList.contains(className)) {
// Fetch from cache first
ISyringe autowiredHelper = classCache.get(className);
// Create objects without caching
if (null == autowiredHelper) { // No cache.
autowiredHelper = (ISyringe) Class.forName(instance.getClass().getName() + SUFFIX_AUTOWIRED).getConstructor().newInstance();
}
// Complete dependency injection
autowiredHelper.inject(instance);
// Put in cache
classCache.put(className, autowiredHelper);
}
} catch (Exception ex) {
// If something goes wrong, you will be added to the blacklist
blackList.add(className); // This instance need not autowired.
}
}
}among ISyringe Is the interface extracted by dependency injection ,
public interface ISyringe {
void inject(Object target);
}that ISyringe Who is the implementation class of ? The answer is automatically generated classes at compile time XXXX
Autowired , Let's find demo Generated in the Test1Activity
Autowired Let's see
public class Test1Activity$$ARouter$$Autowired implements ISyringe {
private SerializationService serializationService;
@Override
public void inject(Object target) {
serializationService = ARouter.getInstance().navigation(SerializationService.class);
Test1Activity substitute = (Test1Activity)target;
substitute.name = substitute.getIntent().getStringExtra("name");
substitute.age = substitute.getIntent().getIntExtra("age", substitute.age);
substitute.height = substitute.getIntent().getIntExtra("height", substitute.height);
substitute.girl = substitute.getIntent().getBooleanExtra("boy", substitute.girl);
substitute.ch = substitute.getIntent().getCharExtra("ch", substitute.ch);
substitute.fl = substitute.getIntent().getFloatExtra("fl", substitute.fl);
substitute.dou = substitute.getIntent().getDoubleExtra("dou", substitute.dou);
substitute.ser = (com.alibaba.android.arouter.demo.testinject.TestSerializable) substitute.getIntent().getSerializableExtra("ser");
substitute.pac = substitute.getIntent().getParcelableExtra("pac");
if (null != serializationService) {
substitute.obj = serializationService.parseObject(substitute.getIntent().getStringExtra("obj"), new com.alibaba.android.arouter.facade.model.TypeWrapper<TestObj>(){}.getType());
} else {
Log.e("ARouter::", "You want automatic inject the field 'obj' in class 'Test1Activity' , then you should implement 'SerializationService' to support object auto inject!");
}
if (null != serializationService) {
substitute.objList = serializationService.parseObject(substitute.getIntent().getStringExtra("objList"), new com.alibaba.android.arouter.facade.model.TypeWrapper<List<TestObj>>(){}.getType());
} else {
Log.e("ARouter::", "You want automatic inject the field 'objList' in class 'Test1Activity' , then you should implement 'SerializationService' to support object auto inject!");
}
if (null != serializationService) {
substitute.map = serializationService.parseObject(substitute.getIntent().getStringExtra("map"), new com.alibaba.android.arouter.facade.model.TypeWrapper<Map<String, List<TestObj>>>(){}.getType());
} else {
Log.e("ARouter::", "You want automatic inject the field 'map' in class 'Test1Activity' , then you should implement 'SerializationService' to support object auto inject!");
}
substitute.url = substitute.getIntent().getStringExtra("url");
substitute.helloService = ARouter.getInstance().navigation(HelloService.class);
}
} From the automatically generated code above , Dependency injection is actually used internally getIntent.getXxxExtra In the form of ( Empathy ,Fragment It's using getArguments().getXxx() ). It should be noted that ,@Autowired The decorated field cannot be private Of , Otherwise, an error will be reported when automatically generating code .
in addition , There's one in the code above SerializationService What is it for ? Actually SerializationService yes json For serialization . stay demo An implementation class is officially given in JsonServiceImpl , Alibaba's is used internally fastjson . If there are children's shoes that need to be customized , You can refer to JsonServiceImpl Do it yourself .
end
See this , Basically ARouter That's all about dependency injection .
This series comes down ,ARouter The process at the code level is almost the same . The rest is gradle-plugin and compiler These two parts have not been resolved , I'll tell you later .
bye bye
边栏推荐
- QT basic hand training applet - simple calculator design (with source code, analysis)
- 【AUTOSAR-RTE】-2-Composition,Component和VFB的介绍
- MySQL中各类型文件详解
- Window源码解析(三):Window的更新机制
- matlab基本操作
- 2022牛客多校第一场补题
- JDBC连接数据库
- Window source code analysis (III): window update mechanism
- F - jealous two-dimensional reverse order pair
- opencv安装配置测试
猜你喜欢

JS array is de duplicated, the ID is the same, and a value is added and merged

How promise instance solves hell callback

ShardingSphere之分库分表概念介绍(二)

Personal blog applet

IntelliJ idea associated database
![376. Swing sequence [greedy, dynamic planning -----]](/img/c3/46cdd8c9320c529171cbf963c768a7.png)
376. Swing sequence [greedy, dynamic planning -----]

Opencv4.60 installation and configuration

【广西大学】考研初试复试资料分享

译文推荐 | 调试 BookKeeper 协议 - 无界 Ledger
![[high number] high number plane solid geometry](/img/fc/da6aefed48f4adbaf58995b5e8fa46.png)
[high number] high number plane solid geometry
随机推荐
IJCAI 2022 | the latest overview of graph structure learning: research progress and future prospects
21 day learning challenge - "AUTOSAR from introduction to mastery - practical part"
Opencv4.60 installation and configuration
Hexadecimal representation of negative numbers
对话MySQL之父:代码一次性完成才是优秀程序员
JS array is de duplicated, the ID is the same, and a value is added and merged
Alibaba cloud server setup and pagoda panel connection
matlab基本操作
什么是跨域?如何解决请跨域问题?
Window source code analysis (IV): window deletion mechanism
[autosar-rte] - introduction of 2-component, component and VFB
MATLAB的符号运算
Activiti启报错: Cannot create PoolableConnectionFactory (Could not create connection to database server
[high number] high number plane solid geometry
【日志】日志干什么的?日志工厂是什么?log4j 的配置和使用? log4j.properties 文件配置、log4j jar包坐标
With frequent data leakage and deletion events, how should enterprises build a security defense line?
ARouter源码解析(二)
Regular expressions for positive and negative values
Personal blog applet
2022 safety officer-b certificate examination simulated 100 questions and answers