jug guice presentation

40
Google Guice Kirill Afanasjev Software Architect jug.lv Riga, Latvia

Upload: dmitry-buzdin

Post on 11-Nov-2014

1.411 views

Category:

Technology


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Jug Guice Presentation

Google Guice

Kirill AfanasjevSoftware Architect

jug.lvRiga, Latvia

Page 2: Jug Guice Presentation

Overview

Dependency Injection Why Guice Getting Guice Using Guice Advanced Guice

Page 3: Jug Guice Presentation

Code without DI

public void sendButtonClicked() {

String text = messageArea.getText();

Validator validator = new MailValidator();

validator.validate(text);

MailSender sender = new MailSender();

sender.send(text);

}

Page 4: Jug Guice Presentation

Using factories

public void sendButtonClicked() {

String text = messageArea.getText();

Validator validator = ValidatorFactory.get();

validator.validate(text);

MailSender sender = SenderFactory.get();

sender.send(text);

}

Page 5: Jug Guice Presentation

Testable now

public void testSendButton() {

MockSender mockSender = new MockSender();

SenderFactory.setInstance(mockSender);

MailForm form = new MailForm();

form.getMessageArea().setText("Some text");

form.sendButtonClicked();

assertEquals("Some text", mockSender.getSentText());

SenderFactory.clearInstance();

}

Page 6: Jug Guice Presentation

Well, not really

public void testSendButton() {

MockSender mockSender = new MockSender();

SenderFactory.setInstance(mockSender);

try {

MailForm form = new MailForm();

form.getMessageArea().setText("Some text");

form.sendButtonClicked();

assertEquals("Some text", mockSender.getSentText());

} finally {

SenderFactory.clearInstance();

}

}

Page 7: Jug Guice Presentation

Dependency injection

private Validator validator;

private MailSender mailSender;

public MailForm(Validator validator, MailSender mailSender) {

this.validator = validator;

this.mailSender = mailSender;

}

public void sendButtonClicked() {

…..

Page 8: Jug Guice Presentation

Testing now

public void testSendButton() {

MockSender mockSender = new MockSender();

Validator validator = new Validator();

MailForm form = new MailForm(validator, mockSender);

form.getMessageArea().setText("Some text");

form.sendButtonClicked();

assertEquals("Some text", mockSender.getSentText());

}

Page 9: Jug Guice Presentation

Why DI frameworks

Avoid boilerplate code AOP Integrate your DI with http session/request,

data access APIs, e.t.c Separate dependencies configuration from

code Makes life easier

Page 10: Jug Guice Presentation

What is Guice

Open source dependency injection framework License : Apache License 2.0 Developer : Google

Page 11: Jug Guice Presentation

Why Guice

Java API for configuration Easier to use Line numbers in error messages Less overhead Less features, too DI in GWT client-side code (using GIN)

Page 12: Jug Guice Presentation

Getting Guice

http://code.google.com/p/google-guice/ http://mvnrepository.com/ Small – 865 KB Version without AOP, suitable for Android –

470KB Lacks fast reflection and line numbers in errors

Page 13: Jug Guice Presentation

Dependency injection with Guice

private Validator validator;

private MailSender mailSender;

@Inject

public MailForm(Validator validator, MailSender mailSender) {

this.validator = validator;

this.mailSender = mailSender;

}

Page 14: Jug Guice Presentation

Creating instance of MailForm

Injector injector =

Guice.createInjector(new YourAppModule());

MailForm mailForm = injector.getInstance(MailForm.class);

Page 15: Jug Guice Presentation

Bindings

public class YourAppModule extends AbstractModule {

protected void configure() {

bind(MailService.class).to(MailServiceImpl.class);

bind(Validator.class).to(ValidatorImpl.class);

}

}

Page 16: Jug Guice Presentation

Providers

public class YourAppModule extends AbstractModule {

protected void configure() {

bind(Validator.class).to(ValidatorImpl.class);

}

@Provides

MailService getMailService() {

MailService service = new MailService();

return service;

}

….

Page 17: Jug Guice Presentation

Injecting fields

@Inject

private Validator validator;

@Inject

private MailSender mailSender;

public MailForm() {

}

Page 18: Jug Guice Presentation

Injecting with setter methods

private Validator validator;

public MailForm() {

}

@Inject

public void setValidator(Validator validator) {

this.validator = validator;

}

Page 19: Jug Guice Presentation

Optional injection

Inject(optional=true) Ignores values for which no bindings are

avalaible Possible with setter methods only

Page 20: Jug Guice Presentation

Bind instance

protected void configure() {

bind(Integer.class).annotatedWith(ThreadCount.class).toInstance(4);

}

..

@ThreadCount

int threadCount;

IDE autocomplete, find usages e.t.c

Page 21: Jug Guice Presentation

Two implementations

protected void configure() {

bind(Validator.class).to(ValidatorImpl.class);

bind(Validator.class).to(StrictValidatorImpl.class);

}

Page 22: Jug Guice Presentation

Two implementations

Exception in thread "main" com.google.inject.CreationException:

Guice configuration errors:

1) Error at lv.jug.MailService.configure(YourAppModule.java:12):

A binding to lv.jug.MailService was already configured at

lv.jug.YourAppModule.configure(YourAppModule.java:11)

Page 23: Jug Guice Presentation

Two implementations

protected void configure() {

bind(Validator.class).to(ValidatorImpl.class);

bind(Validator.class)

.annotatedWith(Strict.class)

.to(StrictValidatorImpl.class);

}

….

@Inject

public MailForm(@Strict Validator validator) {

this.validator = validator;

}

Page 24: Jug Guice Presentation

Binding annotation

@Retention(RetentionPolicy.RUNTIME)

@Target({ElementType.FIELD, ElementType.PARAMETER})

@BindingAnnotation

public @interface Strict {}

Page 25: Jug Guice Presentation

Implicit binding

@Inject

public MailForm(

@ImplementedBy(StrictValidator.class) Validator Validator validator,

MailSender mailSender) {

this.validator = validator;

this.mailSender = mailSender;

}

Page 26: Jug Guice Presentation

Static injection

protected void configure() {

bind(Validator.class).to(ValidatorImpl.class);

requestStaticInjection(OurClass.class);

}

@Inject static Validator validator;

Page 27: Jug Guice Presentation

Scoping

protected void configure() {

bind(Validator.class).to(ValidatorImpl.class)

.in(Scopes.SINGLETON);bind(MailService.class).to(MailServiceImpl.class)

.asEagerSingleton();}

Page 28: Jug Guice Presentation

Multibindings

Multibinder<Plugin> pluginBinder = Multibinder.newSetBinder(binder(), Plugin.class);

pluginBinder.addBinding().to(SomePluginImpl.class);

pluginBinder.addBinding().to(AnotherPluginImpl.class);

….

@Inject Set<Plugin> plugins

Page 29: Jug Guice Presentation

Grapher

Describe the object graph in detail Show bindings and dependencies from several

classes in a complex application in a unified diagram

Generates .dot file

Page 30: Jug Guice Presentation

Advanced Guice

AOP Warp Google Gin Spring integration Using guice with Servlets

Page 31: Jug Guice Presentation

Why AOP

Transaction handling Logging Security Exception handling e.t.c

Page 32: Jug Guice Presentation

AOP

void bindInterceptor(

Match <? super Class<?>> classMatcher,

Matcher<? super Method> methodMatcher,

MethodInterceptor... interceptors)

public interface MethodInterceptor extends Interceptor {

Object invoke (MethodInvocation invocation) throws Throwable

}

Page 33: Jug Guice Presentation

AOP

You can not match on private and final methods due to technical limitations in Java

Only works for objects Guice creates

Page 34: Jug Guice Presentation

Warp

http://www.wideplay.com/ Eco-system for Google Guice Thin lightweight modules for Guice applications Persistence Transactions Servlets

Page 35: Jug Guice Presentation

Warp-persist

Supports : Hibernate/JPA/Db4Objects Inject DAOs & Repositories Flexible units-of-work Declarative transaction management

( @Transactional ) Your own AOP for transactions management @Finder(query="from Person")

Page 36: Jug Guice Presentation

Google Gin

Automatic dependency injection for GWT client-side code

Code generation Little-to-no runtime overhead, compared to

manual DI Uses Guice binding language http://code.google.com/p/google-gin/

Page 37: Jug Guice Presentation

Spring integration

http://code.google.com/p/guice-spring/ @Named(”mySpringBean”)

Page 38: Jug Guice Presentation

JSR-330

javax.inject @Inject @Named @Qualifier @Scope @Singleton e.t.c Supported by Guice, Spring, EJB

Page 39: Jug Guice Presentation

Using Guice with Servlets

@RequestScoped @SessionScoped ServletModule serve(”/admin”).with(AdminPanelServlet.class) serve("*.html", "/my/*").with(MyServlet.class) filter(”/*”).through(MyFilter.class) @Inject @RequestParameters Map<String,

String[]> params;

Page 40: Jug Guice Presentation

Thank you

Questions ?