使 class 可注入和仅带有 Dagger 注释的单例

Make a class injectable and a singleton with Dagger annotation only

我知道有关于如何使用 Module 定义单例的教程。但我的问题不在于此。我的意思是 Dagger 还提供了一种方法,通过注释 class 的空构造函数而不在 Module 中声明任何内容,使 class 可注入到 Android 组件,对吗?例如

public class MyApi {

    @Inject
    public MyApi(){
    }
}

所以,我可以通过 :

MyApi 注入 Fragment
class MyFragment extends Fragment {
   @Inject
   protected MyApi myApi;
   ...
}

这样,MyApi就不需要在Module中手动声明了。 Dagger 懂的

我的问题是,如果我希望 MyApi 成为一个单例,我可以简单地添加一个注释,例如:

public class MyApi {
    @Inject
    @Singleton
    public MyApi(){
    }
}

dagger 会理解它应该是一个单例吗?或者我是否必须在 Module 中声明,例如:

@Module
public class MyModule {

    @Provides
    @Singleton
    MyApi providesMyApi() {
        return new MyApi();
    }
}

?

对于所需的行为,您需要在 class 而不是构造函数上应用注释。看看:

 @Singleton
 public class MyApi {

     @Inject
     public MyApi(){
     }
 }

首先,在 class 之上添加 @Singleton

@Singleton
public class MyApi {
    @Inject
    public MyApi() {}
 }

其次,您需要在 component 界面之上添加 @Singleton

@Singleton
@Component
interface AppComponent {

如果您有兴趣,这里有完整的 kotlin 指南:https://medium.com/@xiwei/simplest-dagger-example-920bbd10258