How to avoid having injector.createInstance() all over the place when using guice?

前端 未结 3 2018
故里飘歌
故里飘歌 2020-12-30 05:28

There\'s something I just don\'t get about guice: According to what I\'ve read so far, I\'m supposed to use the Injector only in my bootstrapping class (in a standalone appl

3条回答
  •  旧巷少年郎
    2020-12-30 05:51

    Yes, you basically only should use the Injector to create get the instance for the root-object. The rest of the application shouldn't touch the Guice-Container. As you've noticed, you still need to create some objects when required. There are different approaches for doing that, each suitable for different needs.

    Inject a Provider Provider is a interface from Guice. It allows you to request a new instance of a object. That object will be created using Guice. For example.

     class MyService{
         private Provider transactionProvider;
         public MainGui(Provider transactionProvider){
             this.transactionProvider = transactionProvider;
         }
    
         public void actionStarted(){
             Transaction transaction = transactionProvider.get();
         }
    

    Build a Factory Often you need some kind of factory. This factory uses some injected services and some parameters and creates a new object for you. Then you use this factory for new instances. Then you inject that factory and use it. There also help for this with the AssistedInject-extension

    I think with these two possibilities you rarely need to use the Guice-Injector itself. However sometimes is still appropriate to use the injector itself. Then you can inject the Injector to a component.

提交回复
热议问题