※不废话直接撸代码,看完你就会Dagger2(最基本的使用)
创建maven工程,导入依赖
pom文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>TestDagger</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>com.google.dagger</groupId>
<artifactId>dagger</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>com.google.dagger</groupId>
<artifactId>dagger-compiler</artifactId>
<version>2.2</version>
<optional>true</optional>
</dependency>
</dependencies>
</project>
创建Module类,用来为对象类提供实例
本例中TestModule为MyApplication类提供实例,其中:
1,provideTestObject()方法为MyApplication.testObject属性提供实例
2,provideString()方法为MyApplication.testStr属性(通过构造器注入)提供实例
package mytest;
import dagger.Module;
import dagger.Provides