Guice @Provides Methods vs Provider Classes

后端 未结 2 989
轮回少年
轮回少年 2020-12-10 14:12

I\'m working on a fairly large project that has a lot of injections. We\'re currently using a class that implements Provider for each injection that needs one,

2条回答
  •  余生分开走
    2020-12-10 14:58

    There is also a difference in how classes are instantiated. For Eg :

    public class GumProvider implements Provider {
    
      public Gum get() {
        return new Gum();
      }
    }
    

    public class GumModule extends AbstractModule {
    
        protected void configure() {
    
            bind(Gum.class).toProvider(GumProvider.class);
            //bind(Gum.class).to(GumballMachine.class);
        }
    }
    

    public class GumballMachine {
    
        @Inject
        private Provider gumProvider;
    
        Gum gum;
    
    
        public Gum dispense() {
            return gumProvider.get();
        }
    }
    

    public class App {
    
        public static void main(String[] args) {
          // TODO Auto-generated method stub
          Injector injector = Guice.createInjector(new GumModule());
          GumballMachine m = injector.getInstance(GumballMachine.class);
          System.out.println(m.dispense());
          System.out.println(m.dispense());
    
    
        }
    
    }
    

    This would create an Instance of Gum Per Invocation. Whereas if @Provides were used the same Instance of Gum would be passed to both the Injectors

提交回复
热议问题