java - Guice: How to do late binding? -
i trying late binding using 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 binding in module:
bind(myclass.class).toprovider(myclassprovider.class).in(servletscopes.request);
i have class consumerclass, needs utilize myclass. here problem comes, because dep null until point, won't able inject myclass consumerclass, hence injected provider.
public class consumerclass { private myclassprovider myclassprovider; @inject public consumerclass(provider<myclass> myclassprovider){ this.myclassprovider = myclassprovider; } ...... public void myfunction() { // here dep initialized , become non-null here. // then, phone call myclass myclass = myclassprovider.get(); } }
the problem have when inject myclassprovider consumerclass, tried create instance of myclassprovider, because dep null @ time, failed. annotating @nullable not solve problem need dep in get() method of provider anyway.
is there ways allow guice create provider instance when get() method called? or there other work around on problem?
many thanks.
jeff: reply.
do mean can alter code 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); } }
replace dependencyclass
provider<dependencyclass>
. guice not require toprovider
or @provides
method in order access provider type guice can provide.
this way dep
need provided when myprovider called, not instantiated.
java guice
No comments:
Post a Comment