Dagger 2没有模块注入单身

Nik*_*ber 4 java android dependency-injection dagger-2

我正在使用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();
    }
}
Run Code Online (Sandbox Code Playgroud)

它工作正常,但现在我想让我的依赖单身.我怎样才能实现它?我应该为这个依赖项创建模块,并使用单例注释注释提供方法,或者我有其他选项来避免模块创建?

Kon*_*iak 8

在类的顶部添加@Singleton并将@Singleton注释添加到组件中.

@Singleton
public class Dependency {

    @Inject
    Dependency() {
    }

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

@Singleton
@Component
public interface ClientComponent {
    void inject(Client client);
}
Run Code Online (Sandbox Code Playgroud)

您还应该将组件的创建移动到更好的位置 - 来自app对象的onCreate方法是正确的位置.