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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With