Reputation: 725
So I need to work on a Guice project that I inherited from a developer who worked on it earlier, and I have a specific problem to address. Let me briefly introduce the application design.
MyService.java
public static void main(String[] args) {
Injector injector = createInjector(new MyModule());
}
MyModule.java
// ...
@Inject
@Provides
@Singleton
public Client getClient(@Named("config") String config) {
// Client should be singleton
return new Client(config);
}
And now is the problem that I have to write the service operation that uses the Client
which exists as a singleton somewhere in the application, but I don't know what would be the good way to obtain it. I need something like the following.
ServiceOperations.java
// ...
public String getData() {
// somehow obtain that client - how?
// and then call operations on the client
return client.getData();
}
If it wasn't Guice, I would just have a ClientFactory
, and call something like ClientFactory.getClientInstance()
from my getData()
method and have the client reference, but with Guice, what is the proper way to obtain it?
PS. I am just learning Guice. Thanks!
Upvotes: 2
Views: 859
Reputation: 6689
Since you already have a provider for the Client
object, it should be straightforward from here:
class ServiceOperations {
@Inject
public ServiceOperations(Client client) {
this.client = client;
}
public String getData() {
return client.getData();
}
}
Magical stuff, right?
Upvotes: 3