guice in athena
DESCRIPTION
Google Guice usageTRANSCRIPT
request/response flow
GuiceFilter LogFilter JsonpFilterGuiceCont
ainer
HttpServlet(servlet)ServletContainer (Jersey)
NewsResource
service(res, resp)
doFilter(res, resp)
doFilter(res, resp)
doFilter(res, resp)handle
Server
dispatch
Init
doStart
ServerGuiceServletContextListener
contextInitialized
ServletContextListener(servlet)
getInjector
Guice
createInjector
InternalInjectorCreator
build
ConstructorInjector
construct
MembersInjector
NewsResource()
loadEagerSingletons
NewsResource
memberInject
construct
Guice : Motivation
• 我们遇到的问题
– Reused code seems hard
– Class and Package boundary/layer is vague/fuzzy
Guice : Motivation
• dependency injection framework
• Easier to
– change
– unit test
– reuse in other contexts
• Modularity
Guice : principle (目的)
• Separate implementation from interface• Decouple concrete from concrete
• IOC principle– reusable code and the problem-specific code are developed
independently
• Dependency Inversion principle– High-level modules should not depend on low-level
modules. Both should depend on abstractions.– Abstractions should not depend on details. Details should
depend on abstractions.
Guice : 如何使用
• 1) Inject
– Constructor
– Method
– Field
Athena 中主要是Field,如果构造函数中使用依赖,则到则使用Constructor
Guice : 如何使用
• 2) Binding
– Linked Bindings
• bindings map a type to its implementation
– Untargeted Bindings
• concrete classes and types annotated by either @ImplementedBy or @ProvidedBy
– Binding Annotations
Guice : 如何使用
• 3) Module
– A module is a collection of bindings
– Install other modules
代码模块化
M1 M2 M3
Minstall
type1
type2
type3
bind
Guice : Inside
• Injector
– Graph construction
– Binding Resolution
– ClassLoader
• AOP
– Reflection vs. codegen