RoboGuice:使用全反射。尝试使用 RoboGuice 注释处理器以获得更好的性能

RoboGuice: Using full reflection. Try using RoboGuice annotation processor for better performance

当我启动我的 RoboGuice android 应用程序时,以下消息出现在日志中:

roboguice.RoboGuice﹕ Using full reflection. Try using RoboGuice annotation processor for better performance.

这是什么意思?

我所有的活动(包括我的 MainActivity)都来自 RoboGuice 的 类。也许我遗漏了一些东西,并且有一种方法可以提高我目前没有做的 RoboGuice 性能。

注意:我正在使用 RoboBlender

我推荐你使用butterknife。如果你使用 android studio 就容易多了,它还有一个插件,让你只需点击一下就可以生成自动视图注入:

有用的文档:https://github.com/avast/android-butterknife-zelezny

RoboGuice基于GoogleGuice库,是一个基于反射的依赖注入框架。不幸的是,Guice 在 Android 上表现不佳。例如,在我最近的项目中,初始化一个注入器需要 1 到 1.5 秒。

在某个时刻,RoboGuice 开发人员决定通过在编译时做一些工作来提高他的库的性能,这就是 RoboBlender 的目的。它在编译时创建一个注释数据库,RoboGuice 在运行时使用它来搜索注入点。您可以向 Guice 阅读更多关于 RoboBlender here. This approach required a lot of changes in Guice so the RoboGuice author had to fork it and even sent a pull request 的信息。但是这个PR被拒绝主要是因为它与Guice库(做一个运行时DI框架)的想法相矛盾。

抱歉介绍了这么长的时间,这里是对您问题的回答。调用 RoboGuice.setUseAnnotationDatabases(false) 时,您要求 RoboGuice 通过反射在运行时处理所有内容。换句话说,RoboGuice 的工作方式与原始 Guice 一样,而且速度不是很快。当您尝试使用注释数据库并且您的应用程序崩溃时,可能会因为找不到注释数据库而发生崩溃。也许你忘了添加 <meta-data android:name="roboguice.annotations.packages" android:value="..."/>AndroidManifest.xml?

最后,我不建议你在 Android 上使用 Guice 或 RoboGuice,因为前者非常慢,而后者被设计坏了。使用诸如 Dagger 之类的编译时 DI 库要好得多,切换到它应该不会花费很多时间。

Roboguice 现已移至版本 4.0.0。这在 github 上可用,作为分支 rg-4-final。在 gradle 中,您可以将其用作

compile 'org.roboguice:roboguice:4.0.0'
provided 'org.roboguice:roboblender:4.0.0'

我之前在让 Roboblender 工作时遇到过问题,但在 4.0.0 中它就像一个魅力。

虽然有变化。查看 Astroboy 示例以了解如何使用它。您不再扩展 Activities 或 Fragments,而是像这样在每个 Activity 或 Fragments 中注入成员:

RoboGuice.getInjector(this).injectMembers(this);

他们放弃了 @InjectView@InjectResource,您现在使用 Butterknife 注入视图,并以正常 Android 方式获取资源。不要忘记在您的应用程序中初始化 Roboguice:

RoboGuice.setupBaseApplicationInjector(this, new MyModule(), new OtherModule());

尽情享受吧!