Created
January 26, 2019 11:56
-
-
Save jixiaoyong/fec4426183328346b955f62eb6e9c91a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Dagger2_basic_guide_line_part3 | |
/** | |
* author: jixiaoyong | |
* email: jixiaoyong1995@gmail.com | |
* website: https://jixiaoyong.github.io | |
* date: 2019/1/26 | |
* description: 介绍了Dagger 2 中的 @Inject 、 @Component 、 | |
@Module 、 @Provides 、@Named 和 @Qualifier 的使用 | |
并且实现了自己的注解 @Choose 支持有多个构造函数的Service类 | |
这一点可以从 | |
fun main() { | |
val client = Client() | |
} | |
打印出 | |
Args | |
default | |
得到验证 | |
*/ | |
class Service(var string: String = "default") | |
class Client{ | |
//@field:是kotlin中注解字段特别需要的,在Java中可以直接写成@Named("Args") | |
@Inject | |
@field:Choose("Args") | |
lateinit var service0: Service | |
@Inject | |
lateinit var service1: Service | |
init { | |
DaggerClientComponent.create().inject(this) | |
// DaggerClientComponent.builder().build().inject(this) | |
println(service0.string) | |
println(service1.string) | |
} | |
} | |
@Component(modules = [ClientModule::class]) | |
interface ClientComponent{ | |
fun inject(client: Client) | |
} | |
@Module | |
class ClientModule{ | |
@Provides | |
fun getService() = Service() | |
@Provides @Choose("Args") | |
fun getServiceWithArgs() = Service("Args") | |
} | |
@Qualifier | |
@MustBeDocumented | |
@kotlin.annotation.Retention(AnnotationRetention.RUNTIME) | |
annotation class Choose(//Choose可以是任意你喜欢的名字 | |
/** The name. */ | |
val value: String = "" | |
) | |
fun main() { | |
val client = Client() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment