简体   繁体   English

Dagger 2没有模块注入单身

[英]Dagger 2 inject singleton without module

I am using Dagger 2 injection to provide some dependency to client: 我正在使用Dagger 2注入为客户端提供一些依赖:

public class Dependency {

    @Inject
    Dependency() {
    }

    void check() {
        System.out.print("Instantiated");
    }
}

public class Client {

    @Inject Dependency dependency;

    Client() {
        ClientComponent component = DaggerClientComponent.create();
        component.inject(this);
    }

    void checkDependency() {
        dependency.check();
    }
}

@Component
public interface ClientComponent {
    void inject(Client client);
}

public class Test {
    public static void main(String... args) {
        Client client = new Client();
        client.checkDependency();
    }
}

It works fine, but now I want to make my dependency singleton. 它工作正常,但现在我想让我的依赖单身。 How can I achieve it? 我怎样才能实现它? Should I create module for this dependency and annotate provide method with singleton annotation or I have another options to avoid module creation? 我应该为这个依赖项创建模块,并使用单例注释注释提供方法,或者我有其他选项来避免模块创建?

Add @Singleton on the top of your class and add @Singleton annotation to your component. 在类的顶部添加@Singleton并将@Singleton注释添加到组件中。

@Singleton
public class Dependency {

    @Inject
    Dependency() {
    }

    void check() {
        System.out.print("Instantiated");
    }
}

@Singleton
@Component
public interface ClientComponent {
    void inject(Client client);
}

You should also move creation of your component to better place - onCreate method from app object is right place. 您还应该将组件的创建移动到更好的位置 - 来自app对象的onCreate方法是正确的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM