Dagger使用

来源:互联网 发布:网络老虎机揭秘 编辑:程序博客网 时间:2024/05/01 08:21

1、在android项目中使用注解有一些开源项目,比如annotation,roboguice,但是因为他们都是运行时使用注解(反射)会影响

性能,因而一直没有在项目中使用,今天偶尔看到了另外一个开源的项目:dagger,按照官方的文档,他是在编译的时候生成

了相应的代码,因而性能上可以忽略了,所以花点时间学习一下使用

2、首先,是运行官方的demo->coffee,该项目依赖四个jar,分别为 dagger-1.2.2.jar,javax.inject-1.jar,dagger-compiler-1.2.2.jar,javawriter-2.5.1.jar

这个项目的部署,参考这里http://scouse.com/adding-dagger-to-an-android-eclipse-project/

2.1)Create two subdirectories within your project, the first called “libs” 
and the second called “compile-libs”.
2.2)Add the dagger.jar and javax.inject.jar files into the libs directory, 
(I used dagger-1.2.0.jar for my current project).
2.3)Add the dagger-compiler.jar and javawriter.jar files to the compile-libs directory, 
(I used dagger-compiler-1.2.0.jar and javawriter-2.2.1.jar).
2.4)Open up the Properties panel for the project and select “Java Compiler” 
then ensure “Enable project specific settings” checkbox is selected.
2.5)Next expand the “Java Compiler” navigation element on the left and select “Annotation Processing” 
and again ensure the “Enable project specific settings” check box is selected. 
Then check the “Enable annotation processing” check box and ensure the “Generated source 
directory:” text field contains “.apt_generated”
2.6)Expand the “Annotation Processing” navigation element on the left and select “Factory Path”. 
Then click “Add Jars” in the panel and select all four of the jars added to the libs 
and compile libs in steps 2 and 3 above.
2.7)Next click on the “Java Build Path” and ensure that 
the “.apt_generated” entry appears on the source tab
2.8)Finally click on the Libraries tab and ensure that the dagger.jar 
and javax.inject.jar files appear in the list of JAR’s 
and class folders on the build path. (If they are not there, add them).

3、关于具体使用参考http://square.github.io/dagger/,这里只是简要介绍一下

3.1)对于程序可控的类使用@Inject注解的方式实例化对象

3.2)对于接口、第三方类、Configurable objects must be configured要使用@Provides注解方式实例化对象

3.3)以@Provides注解的方法必须要包含在一个module中(@Module注解

3.4)为便于阅读,@Module注解的类以Module为后缀,@Provides注解的方法以provide为前缀

3.5)以@Inject和@Provides注解的类形成了一张对象图( a graph of objects),该graph可以通过ObjectGraph.create()来获取

3.6)@Singleton注解方法或是类,graph中唯一的实例

3.7)Lazy<T>,在没有调用get方法之前T对象不会实例化,如果T是@Singleton,那么在一个graph中只有一个对象,否则每@Inject一次生成一个新对象

3.8)还有一些其他的使用规则看官方文档吧






0 0
原创粉丝点击