Reputation: 3
I am implementing a Service Oriented Architecture system. There are some classes in my system that talk to an external API, so there must be some way that we can instantiate these classes when I start my program, so that they don't have to be instantiated every time someone sends a request. I was wondering if Google Guice would have something like that but so far I have found that Google Guice is good for choosing implementation class for an interface, and for by-need instantiation.
To make my question more clearer, let's say ClassAPIUser is the class which calls an external API, and it is the class I would like to instantiate in the beginning (static void main method). And let's say ClassCaller has a field of ClassAPIUser. I would like to find a way so that I can tell my program to fetch the already-instantiated ClassAPIUser from the main method (the entry-point) :
> public class ClassCaller {
>
> private ClassAPIUser classAPIUser;
>
> // Constructor
> public ClassCaller (ClassAPIUser classAPIUser) {
> this.classAPIUser = classAPIUser;
> }
> }
Is there a way I can use Google Guice to let ClassCaller know that classAPIUser is the one instantiated in the static void main method? Also, what should I be specifying in the static void main method and how should I be instantiating ClassAPIUser in the static void main method?
Upvotes: 0
Views: 2471
Reputation: 728
By default, Guice returns a new instance each time it supplies a value. This behaviour is configurable via scopes. Scopes allow you to reuse instances: for the lifetime of an application (@Singleton), a session (@SessionScoped), or a request (@RequestScoped). Guice includes a servlet extension that defines scopes for web apps. Custom scopes can be written for other types of applications.
Singleton
is what you want. Take a look at the documentation.
Upvotes: 1