Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use @Singleton of Guice ?

Tags:

android

guice

I need to make one instance of some class - and this one instance need to be accessible from any place in the code.

So, I found the Guice... and i want to use the '@Singleton' from this package but i don't find any example or some doc to how to use it and how to make the declaration.

like image 338
Yanshof Avatar asked Dec 16 '22 06:12

Yanshof


1 Answers

@Singleton is very easy to use. It just goes like this

@Singleton
public class A {

    @Inject
    public A() {
    }
}

Please note however that the singleton is one per injector and not per VM. Singleton is a scope type and GUICE also allows custom scopes which can be very useful. Please see links below.

When you use this in another class you just need to inject it.

public class B {
   @Inject
   public B(A a) {
   }
}

http://code.google.com/p/google-guice/wiki/Scopes

http://code.google.com/p/google-guice/wiki/GettingStarted

like image 199
Sid Malani Avatar answered Jan 12 '23 20:01

Sid Malani