guice in athena

24
Guice in Athena 2014/11/28 datayes.com

Upload: alexander-lee

Post on 07-Jul-2015

69 views

Category:

Technology


0 download

DESCRIPTION

Google Guice usage

TRANSCRIPT

Guice in Athena

2014/11/28 datayes.com

• Request/Response Flow

• Init

• Guice

– Motivation? 解决什么问题

–如何使用

–原理和机制 (Inside)

request/response flow

AthenaServlet

doGet(res, resp)handle

Server

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

Request/Response Stack

No new instance

Jersey

Guice new NewsResource

new NewsMapper

Init

doStart

ServerGuiceServletContextListener

contextInitialized

ServletContextListener(servlet)

getInjector

Guice

createInjector

InternalInjectorCreator

build

ConstructorInjector

construct

MembersInjector

NewsResource()

loadEagerSingletons

NewsResource

memberInject

construct

Init

Guice : Motivation

• 我们遇到的问题

– Reused code seems hard

– Class and Package boundary/layer is vague/fuzzy

Guice : Motivation

• Why Guice?Elasticsearch heavily build on Guice

InternalNode.java

Guice : Motivation

• dependency injection framework

• Easier to

– change

– unit test

– reuse in other contexts

• Modularity

Guice : Modularity

• Modularity

– Elasticsearch

Guice : Modularity

• Modularity

– Elasticsearch

Guice : Modularity

Guice : 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 : DI (手段)

1

3

2

4

DI : clientservice/service implinjector

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 : 如何使用

• 4) Injector

–传入一个/多个 Module

Athena -> GuiceServletConfig

Guice : other

• Scopes

– @singleton

– @ RequestScoped

– @ SessionScoped

• AOP

– MethodInterceptor

Guice : Inside

• Injector

– Graph construction

– Binding Resolution

– ClassLoader

• AOP

– Reflection vs. codegen

Reference

• https://www.youtube.com/watch?v=hBVJbzAagfs

• http://www.infoq.com/presentations/Dagger