zhaoyi wrote:
> This is my code. Whenever I call mouseActionFactoryProvider.get(), it
> will return create an instance. It seems that the @Singleton doesn't
> work here.
> 
> @Singleton
> public class MouseActionFactoryProvider implements
> Provider<MouseActionListenerFactory> {
> 
>       @Override
>         @Singleton
>       public MouseActionListenerFactory get() {
>               return new MouseActionListenerFactory();
>       }
> }

Scope annotations apply to providers as a whole, annotating the get()
method with @Singleton is erroneous and ignored.

> public class MouseActionModule extends AbstractModule {
> 
>       @Override
>       protected void configure() {
>               bind(MouseActionListenerFactory.class).toProvider(
>                               
> MouseActionFactoryProvider.class).in(Singleton.class);
>               bind(MouseActionFactoryProvider.class).in(Singleton.class);
>       }
> 
> }

What you have done here is:

1) Bind MouseActionListenerFactory, in singleton scope, to be produced
via your Provider.

2) ENTIRELY SEPARATELY bind a different instance of the Provider as a
second singleton.

> public static void main(String []args){
>                 Injector injector = Guice.createInjector(new
> MouseActionModule());
>               mouseActionFactoryProvider = injector
>                               .getInstance(MouseActionFactoryProvider.class);
> 
> }

And here you retrieve the singleton created by the second binding. Any
calls you make to its get() method are NOT MANAGED by Guice, so each one
runs the get() method afresh.

You should REMOVE the second binding from your Module, and you should
call injector.getProvider(x) in the case above where you are currently
calling injector.getInstance(x).

Max.



Attachment: signature.asc
Description: OpenPGP digital signature

Reply via email to