Created
August 11, 2011 17:18
-
-
Save coderunner/1140227 to your computer and use it in GitHub Desktop.
inject example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //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