简体   繁体   中英

Dagger 2 inject singleton without module

I am using Dagger 2 injection to provide some dependency to client:

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
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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