java - Guice: Inject a class bound by another module? -
i have following classes:
public class cachemodule extends abstractmodule { @override protected void configure() { bindconstant().annotatedwith(names.named(timeout")).to(60); // ...etc. } } public class defaultcacheadaptor implements cacheadaptor { private cachemodule bootstrapper = new cachemodule(); @named("timeout") private int timeout; // other fields omitted brevity public defaultcacheadaptor() { super(); injector injector = guice.createinjector(bootstrapper); @named("timeout") int t = injector.getinstance(integer.class); settimeout(t); } } public class queuemodule extennds abstractmodule { @override public void configure() { bind(cacheadaptor.class).to(defaultcacheadaptor.class); } } public class defaultqueueadaptor implements queueadaptor { private queuemodule bootstrapper = new queuemodule(); private cacheadaptor cacheadaptor; public defaultqueueadaptor() { super(); injector injector = guice.createinjector(bootstrapper); setcacheadaptor(injector.getinstance(cacheadaptor.class)); } }
the cachemodule
/cacheadaptor
/defaultcacheadaptor
located in different jar queuemodule
/queueadaptor
/defaultqueueadaptor
, , latter jar depends on former jar @ runtime (obviously).
the purpose of coding things way allow cachemodule
boostrap/inject entire object graph under defaultcacheadaptor
when user writes:
cacheadaptor cacheadaptor = new defaultcacheadaptor();
ditto queueadaptor
.
it happens queueadaptor
gets injected cacheadaptor
.
however, defaultcacheadaptor
"root" of own object tree, , should always injected cachemodule
.
so ask: how can bind defaultcacheadaptor
cacheadaptor
inside queuemodule
, ensure defaultcacheadaptor
initialized/bootstrapped cachemodule
? in advance!
to honest sounds problem isn't 1 of guice, instead standard problem across software engineering: ensuring dependencies claim do. queuemodule shouldn't concern whether defaultcacheadaptor holds general contract. instead, write unit test defaultcacheadaptor guarantees bootstraps itself, use in queuemodule without second thought.
this true because defaultcacheadaptor has unrelated injector tree. should able use defaultcacheadaptor opaquely, , stop concerning queueadaptor implementation details. bootstrapping part of implementation, not api.
even if merge 2 injector graphs 1 (by injecting injector , calling createchildinjector, instance), there's little way guarantee @ compile time bindings need in other modules exist, because module
s work @ runtime. best bet write unit test. can fail little faster calling requirebinding
, fail @ injector creation if particular dependency doesn't end satisfied externally.
Comments
Post a Comment