- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的问题非常简单明了:两个注释/示例之间有什么区别:
@Singleton
class MySingletonClass() {}
@Module
@InstallIn(FragmentComponent::class)
abstract class MyFragmentModule {
@Provides
fun provideMySingletonClass() = MySingletonClass()
}
class MySingletonClass() {}
@Module
@InstallIn(FragmentComponent::class)
abstract class MyFragmentModule {
@Singleton
@Provides
fun provideMySingletonClass() = MySingletonClass()
}
我知道的唯一区别是,第二个示例给我以下错误:
error: [Dagger/IncompatiblyScopedBindings] FragmentC scoped with @dagger.hilt.android.scopes.FragmentScoped may not reference bindings with different scopes:
这是否意味着示例 1 中的 @Singleton
注释被简单地忽略了?
最佳答案
在示例一中,您的@Singleton
注释被忽略,但这只是因为您在@Provides
方法中自己调用构造函数。因为 Dagger 不与您的 MySingletonClass
构造函数交互,所以它无法读取或使用注释。
如果您的 @Singleton class MySingletonClass
有一个 @Inject 构造函数
——即使是一个空构造函数——那么 Dagger 将能够直接与它交互只要 您还删除了将覆盖构造函数检测的 @Provides fun
。完成后,@Singleton
的行为在两种语法中都是相同的。
关于错误消息“错误:[Dagger/IncompatiblyScopedBindings] XXX scoped with @YYY may not reference bindings with different scopes”:@Andrew 这里真正的问题是在示例二中你是尝试在您安装在 FragmentComponent 中的模块中声明 @Singleton 绑定(bind)。 @Singleton 绑定(bind)只能发生在@Singleton 组件中,which in Hilt is SingletonComponent .我记不太清了,但我认为您的示例一(经过我描述的编辑)可以使用单例行为并且不会出现错误,因为 Dagger 会自动选择层次结构中的适当组件来安装您的 MySingletonClass。
关于android - Dagger 柄 : Difference between annotating a class @Singleton and a provides function @Singleton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68865224/
我是一名优秀的程序员,十分优秀!