Guice: How do I make a final commitment?

I am trying so late to contact Google Guice.

public class MyClassProvider implements Provider<MyClass>{
    private DependencyClass dep;
    private WebService webservice;

    @Inject
    MyClassProvider(DependencyClass dep, WebService webservice){
        this.dep = dep;
        this.webservice = webservice;
    }

    public MyClass get() {
        MyClass myclass = webservice.call(dep);
    }
}

      

I have a binding in a module:

   bind(MyClass.class).toProvider(MyClassProvider.class).in(ServletScopes.REQUEST);

      

I have another ConsumerClass that MyClass needs to use. Here the problem occurs because dep will be null up to a certain point, I cannot Inject MyClass for ConsumerClass, so I injected the provider.

public class ConsumerClass {
    private MyClassProvider myClassProvider;

    @Inject
    public ConsumerClass(Provider<MyClass> myClassProvider){
       this.myClassProvider = myClassProvider;
    }

    ......

    public void myfunction() {
        // Here dep is initialized and become non-null here.

        // Then, I call
        MyClass myClass = myClassProvider.get();

    }
}

      

The problem is that when I insert MyClassProvider into ConsumerClass it tried to instantiate MyClassProvider because at that moment dep is null, it failed. Annotating it as @Nullable doesn't solve my problem as I still need the get () method of the provider.

Can Guice be used to instantiate a provider only when the get () method is called? Or is there any other work on this issue?

Many thanks.


Jeff: Thanks for your answer.

You mean that I can change my code to something like:

public class MyClassProvider implements Provider<MyClass>{
        private Provider<DependencyClass> depProvider;
        private WebService webservice;

        @Inject
        MyClassProvider(Provider<DependencyClass> depProvider, WebService webservice){
            this.depProvider = depProvider;
            this.webservice = webservice;
        }

        public MyClass get() {
            DependencyClass dep = depProvider.get(); 
            MyClass myclass = webservice.call(dep);
        }
    }

      

+3


source to share


1 answer


Replace DependencyClass

with Provider<DependencyClass>

. Guice does not require a method toProvider

or @Provides

to access the Provider for any type that Guice can provide.



This way dep

should only be provided when calling MyProvider, not an instance.

+2


source







All Articles