我是dagger2]的新手,正在练习单例,但我面临混乱,我不明白为什么会这样。这是很简单的逻辑:两节课!人与人。人是singleton,人是简单的类,只是@ inject构造函数。当我使人类类单身并在人类类参数的@inject构造函数中使用人并尝试打印一些日志消息并在主要活动中@Inject人类类并调用人类类函数时。它把两个类都显示为一个单例。这是一些代码。人类类
@Singleton class Human @Inject constructor( private var people: People ){ fun human(){ Log.d(Tag,"Human-> $this || People-> $people ") } }
//People Class class People @Inject constructor()
//Component Interface @Singleton @Component interface AppComponent { fun inject(mainActivity: MainActivity) }
主要活动
class MainActivity : AppCompatActivity() { @Inject lateinit var human: Human @Inject lateinit var humanTwo: Human override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val component = DaggerAppComponent.create() component.inject(this) human.human() humanTwo.human() } }
这里是输出
2019-12-05 20:05:01.064 5831-5831/com.example.daggerinjection D/Human: Human-> com.example.daggerinjection.human.Human@49111bd || People-> com.example.daggerinjection.human.People@a5a53b2
2019-12-05 20:05:01.064 5831-5831/com.example.daggerinjection D/Human: Human-> com.example.daggerinjection.human.Human@49111bd || People-> com.example.daggerinjection.human.People@a5a53b2
看到了吗?我称人类类具有不同的实例,但人类和人都充当单身人士,但实际上,人类类在第二个输出中应该是不同的。但是当我这样做时。
人类类
@Singleton class Human @Inject constructor()
//People Class class People @Inject constructor( private var human: Human ) { fun person() { Log.d(Tag,"People -> $this || Human-> $human") } } //Interface is same as above nothing changed
主要活动
class MainActivity : AppCompatActivity() { @Inject lateinit var people: People @Inject lateinit var peopleTwo: People override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val component = DaggerAppComponent.create() component.inject(this) people.person() peopleTwo.person() } }
输出应为:
2019-12-05 20:11:53.292 6107-6107/com.example.daggerinjection D/Human: People -> com.example.daggerinjection.human.People@49111bd || Human-> com.example.daggerinjection.human.Human@a5a53b2
2019-12-05 20:11:53.293 6107-6107/com.example.daggerinjection D/Human: People -> com.example.daggerinjection.human.People@ba20f03 || Human-> com.example.daggerinjection.human.Human@a5a53b2
为什么会这样?
我是dagger2的新手,正在练习单例,但是我面临混乱,我不明白为什么会这样。这是很简单的逻辑:两个类!人与人。人类...
Human
是单例。创建实例后,Dagger将不会创建另一个实例。因此,human2
与human1
相同。由于Dagger不创建其他实例,因此people
变量将相同。