java - How to access the Guice injector throughout application -



java - How to access the Guice injector throughout application -

i've started using guice , after reading docs, skimming through few books , watching 2009 google i/o talk i'm trying convert thrift project relies on few global info structures. @ moment they're created when thrift server starts , passed handler on each request. they're used in every part of code! singletons.

as understand it's best practice create injector in main method , load you're modules once.

i'm not sure how i'm meant utilize injector somewhere else in code. should wrap in singleton class , litter code with

injector injector = injectorinstance.get(); classa obj = injector.getinstance(classa.class);

or there method don't know about

classa obj = guice.getlastinjector().getinstance(classa.class);

i've found recommendation pass around providers i'm not sure how that's improve passing actual info structures downwards phone call stack.

if explain recommended pattern, or improve send me in direction of open source project uses guice grateful!

for guice, thought have entire graph of dependencies, each of keeps reference things needs across lifetime:

class entrypoint { public static void main(string[] args) { yourapp yourapp = guice.createinjector(yourlistofmodules()) .getinstance(yourapp.class); yourapp.run(); } } class yourapp { @inject dependencya dependencya; } class dependencya { @inject dependencyb dependencyb; } class dependencyb { /** injected once, you'll same instance. */ @inject dependencyc dependencyc; /** injecting provider, can multiple instances. */ @inject provider<dependencyd> dependencyd; }

guice takes care of plumbing, yourapp , dependencya don't need worry whether dependencyb needs dependencyc or dependencyd. in sense, never phone call new: guice takes care of creating every @injected dependency you, , supplying dependencies.

if haven't plumbed through dependencies (i.e. still phone call new in code), you'll no longer have access injector manually-constructed class. in case may want utilize getinstance or getprovider , stash away in static field. guice help requeststaticinjection, not great long-term guice design may help work legacy code or transitioning guice.

java guice thrift

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -