Skip to content

Instantly share code, notes, and snippets.

@coderunner
Created August 11, 2011 17:18
Show Gist options
  • Select an option

  • Save coderunner/1140227 to your computer and use it in GitHub Desktop.

Select an option

Save coderunner/1140227 to your computer and use it in GitHub Desktop.
inject example
//create the injector builder
Injector.Builder builder = new Injector.Builder();
//add the bindings
builder.addClassBinding(ConsoleWriter.class, SystemOutConsoleWriter.class);
builder.addSingletonMapping(MessageFormatter.class, MessageFormatter.class);
builder.addObjectMapping(String.class, "Inject Says");
//create the injector
Injector inject = builder.build();
//create the ConsoleWritter
ConsoleWriter writer = inject.createObject(ConsoleWriter.class);
/*
* When creating the ConsoleWriter, the injector will use the bindings and create an
* instance of SystemOutConsoleWriter. But SystemOutCosoleWriter needs to be injected
* a MessageFormatter. So the injector will instantiate a MessageFormatter, that in turn
* needs a String. Since String.class is bound to "Inject Says", this string will be
* injected in the MessageFormatter.
*
* So when calling writer.write("hello!"), "Inject Says: hello!" will be printed!
*/
writer.write("hello!");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment