ARouter源码解析(三)

arouter-api version : 1.4.1

前言

到现在为止,ARouter 还有最后的依赖注入还没有解析过,那么今天就来深入探究一下其实现原理。

PS : 因为依赖注入的原理还比较简单,所以本篇篇幅会较短。

@Autowired解析

想要用 ARouter 实现依赖注入,需要在 Activity/Fragment 中加上

ARouter.getInstance().inject(this);

那么我们这个代码就成为了我们分析的入口了。

public void inject(Object thiz) {
    _ARouter.inject(thiz);
}

ARouter 内部还是调用了 _ARouter 的 inject 方法。

static void inject(Object thiz) {
    AutowiredService autowiredService = ((AutowiredService) ARouter.getInstance().build("/arouter/service/autowired").navigation());
    // 如果 autowiredService 不为空,完成依赖注入
    if (null != autowiredService) {
        autowiredService.autowire(thiz);
    }
}

发现依赖注入和拦截器很相似,都是利用服务组件来完成的。依赖注入的服务组件叫 AutowiredService ,跟踪可以发现,它的实现类是 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 {
            // 如果 instance 这个类进入黑名单了,就不会完成依赖注入
            if (!blackList.contains(className)) {
                // 先从缓存中取
                ISyringe autowiredHelper = classCache.get(className);
                // 没有缓存就创建对象
                if (null == autowiredHelper) {  // No cache.
                    autowiredHelper = (ISyringe) Class.forName(instance.getClass().getName() + SUFFIX_AUTOWIRED).getConstructor().newInstance();
                }
                // 完成依赖注入
                autowiredHelper.inject(instance);
                // 放入缓存中
                classCache.put(className, autowiredHelper);
            }
        } catch (Exception ex) {
            // 出错就加入黑名单中
            blackList.add(className);    // This instance need not autowired.
        }
    }
}

其中 ISyringe 就是依赖注入抽取出来的接口,

public interface ISyringe {
    void inject(Object target);
}

那么 ISyringe 的实现类又是谁呢?答案就是在编译期自动生成的类 XXXX$$ARouter$$Autowired ,我们找 demo 中生成的 Test1Activity$$ARouter$$Autowired 来看看

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);
  }
}

从上面自动生成的代码中看出来,依赖注入实际上内部还是使用 getIntent.getXxxExtra 的形式来赋值的(同理,Fragment 用的是getArguments().getXxx() )。需要注意的是,@Autowired 修饰的字段不能是 private 的,不然在自动生成代码的时候会报错。

另外,上面的代码中有一个 SerializationService 是用来干什么的?其实 SerializationService 是 json 序列化用的。在 demo 中官方给出了一个实现类 JsonServiceImpl ,内部用的是阿里的 fastjson 。如果有需要自定义的童鞋,可以参照着 JsonServiceImpl 自己去实现。

结束

看到这,基本上 ARouter 依赖注入的东西就讲完了。

这一系列下来,ARouter 代码层面的流程都讲的差不多。剩下就是 gradle-plugin 和 compiler 这两个部分还没解析过,等时间了再给大家讲。

bye bye

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容

  • ARouter源码解读 以前看优秀的开源项目,看到了页面路由框架ARouter,心想页面路由是个啥东东,于是乎网上...
    陆元伟阅读 461评论 0 1
  • 终于来到了ARouter解析的第五篇了,前面陆陆续续分享了四篇ARouter框架的使用和源码内容: ARouter...
    juexingzhe阅读 6,694评论 1 8
  • 前言 随着项目业务逻辑和功能点日益递增, 逻辑的耦合程度也逐渐升高, 组件化技术可以很好的解决这个问题, 公司大佬...
    SharryChoo阅读 1,048评论 0 9
  • 我是只很有上进心的猴子,为了“提高”,忍痛割掉了那本该伴我终生的尾巴,幻化成人的模样,混迹其中,模仿着他们的行为,...
    danli227阅读 225评论 0 1
  • 竹篱茅舍柴扉开, 游客如云不长苔。 酒幌飘扬香稻地, 奇花异果李纨栽? 注:稻香村原为贾宝玉的寡嫂李纨的住所。 2...
    江德丰阅读 799评论 20 18