Skip to content

Instantly share code, notes, and snippets.

@jixiaoyong
Created January 26, 2019 11:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jixiaoyong/35714a6287617260d8578c1b716427cb to your computer and use it in GitHub Desktop.
Save jixiaoyong/35714a6287617260d8578c1b716427cb to your computer and use it in GitHub Desktop.
//Dagger2_basic_guide_line_part2
/**
* author: jixiaoyong
* email: jixiaoyong1995@gmail.com
* website: https://jixiaoyong.github.io
* date: 2019/1/26
* description: 介绍了Dagger 2 中的 @Inject 、 @Component
@Module 和 @Provides 的使用
当 @Component 在搜索Service的构造方法时,会先从 @Module 中搜索;
如果搜索不到再到 @Inject 修饰的类中查找。
这一点可以从
fun main() {
val client = Client()
}
打印出 “Provides”而非 “default” 得到验证
*/
class Service @Inject constructor(){
var string: String = "default"
}
class Client{
@Inject
lateinit var service: Service
init {
DaggerClientComponent.create().inject(this)
// DaggerClientComponent.builder().build().inject(this)
println(service.string)
}
}
@Component(modules = [ClientModule::class])
interface ClientComponent{
fun inject(client: Client)
}
@Module
class ClientModule{
@Provides
fun getService() :Service{
val service = Service()
service.string = "Provides"
return service
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment