Google Guice (pronounced "Guice") is a Java framework that does
dependency injection for you.
It is a dependency injector.
You can take advantage of automated object lifetimes
Because you don’t express object-wiring code directly in your code, you can
easily reuse or replace it across the application and beyond
Once objects are in the club, meaning the framework controls their creation
and lifetime, you can do all sorts of things with them, like apply aspectoriented
programming (AOP) advice
Guice Injection Styles
LOCATION | INJECTION ORDER | MOTIVATION | COMMENT |
Constructor | First | Class immutability1 Mandatory dependencies | Only one allowed with @Inject. |
Field | Second | Quick prototyping Code that doesn’t need testin | Injection order is random. |
Setter | Third | Dealing with legacy classes Optional dependencies | Injection order is random. |
One final interesting point to note is that whichever type of injection you use, the
target’s visibility does not matter. Guice will inject anything tagged with @Inject
whether it’s private, package private, protected, or public.
Constructor injection
Constructor injection to the nth
Method injection
Note: only one constructor can be marked with @Inject. If none
are, Guice expects a default constructor.
Modules supply extra information to Guice.
Modules and Applications
• Modules and Applications are many-to-many.
• One Application will usually contain many Modules.
(createInjector() is a varargs method.)
• One Module can be used in any number of different
Applications.
• The granularity of a Module? Whatever you want it to be. A
unit of reuse.
• Modules may install other Modules
• But you may or may not want to do this
• In Guice 1.0 this inclusion graph must be
Named bindings
Constant bindings
provider
Introducing the custom provider
If Guice doesn't know how to create your instances, tell it who
does know.
Scopes
A scope is a policy for reusing injected instances
• Default: no scope
• Create, inject, forget
• Providers are no different - they can have scopes
• Providers don't need to scope what they return (orthogonal)
• com.google.inject defines one scope: Singleton
• You can write your own, too
Field vs. Method vs. Constructor Injection
Field injection
• Most compact syntax (great for slides!)
• Can't take any special action upon injection
• Your class is not testable!
Method injection
• Isn't field injection
• Only thing that works for some strange edge cases
Constructor injection
• Fields can be final
• Cannot possibly have been skipped
• What the idea of construction is all about
• Easy to see dependencies at a glance
• Doesn't support optional injections
• Useless in certain cases, like servlets
• Subclasses need to "know about" the injections needed by
their superclasses
• Less convenient for tests that only "care about" one of the
parameters
What can dependency injection do for me?
• Easier testing
• More decoupling
• Less boilerplate
• Better maintainability
没有评论:
发表评论