SlideShare une entreprise Scribd logo
1  sur  40
Télécharger pour lire hors ligne
Google Guice
  Kirill Afanasjev
 Software Architect




       jug.lv
    Riga, Latvia
Overview

   Dependency Injection
   Why Guice
   Getting Guice
   Using Guice
   Advanced Guice
Code without DI

 public void sendButtonClicked() {
     String text = messageArea.getText();
     Validator validator = new MailValidator();
     validator.validate(text);
     MailSender sender = new MailSender();
     sender.send(text);
 }
Using factories

 public void sendButtonClicked() {
      String text = messageArea.getText();
      Validator validator = ValidatorFactory.get();
      validator.validate(text);
      MailSender sender = SenderFactory.get();
      sender.send(text);
  }
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();
 }
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();
       }
   }
Dependency injection

 private Validator validator;
 private MailSender mailSender;


 public MailForm(Validator validator, MailSender mailSender) {
       this.validator = validator;
       this.mailSender = mailSender;
 }


 public void sendButtonClicked() {
 …..
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());
 }
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
What is Guice

   Open source dependency injection framework
   License : Apache License 2.0
   Developer : Google
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)
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
Dependency injection with Guice

 private Validator validator;
 private MailSender mailSender;


 @Inject
 public MailForm(Validator validator, MailSender mailSender) {
      this.validator = validator;
      this.mailSender = mailSender;
 }
Creating instance of MailForm

 Injector injector =
     Guice.createInjector(new YourAppModule());
 MailForm mailForm = injector.getInstance(MailForm.class);
Bindings

 public class YourAppModule extends AbstractModule {
     protected void configure() {
                bind(MailService.class).to(MailServiceImpl.class);
                bind(Validator.class).to(ValidatorImpl.class);
     }
 }
Providers
 public class YourAppModule extends AbstractModule {
      protected void configure() {
                 bind(Validator.class).to(ValidatorImpl.class);
      }


      @Provides
      MailService getMailService() {
                 MailService service = new MailService();
                 return service;

      }
 ….
Injecting fields

 @Inject
 private Validator validator;
 @Inject
 private MailSender mailSender;


 public MailForm() {
 }
Injecting with setter methods

   private Validator validator;


   public MailForm() {
   }


   @Inject
   public void setValidator(Validator validator) {
               this.validator = validator;
   }
Optional injection

   Inject(optional=true)
   Ignores values for which no bindings are
    avalaible
   Possible with setter methods only
Bind instance

    protected void configure() {
         bind(Integer.class).annotatedWith(ThreadCount.cla
         ss).toInstance(4);
    }
    ..
    @ThreadCount
    int threadCount;

   IDE autocomplete, find usages e.t.c
Two implementations
  protected void configure() {
             bind(Validator.class).to(ValidatorImpl.class);
             bind(Validator.class).to(StrictValidatorImpl.class);
  }
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)
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;
  }
Binding annotation

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@BindingAnnotation
public @interface Strict {}
Implicit binding

      @Inject
      public MailForm(
         @ImplementedBy(StrictValidator.class) Validator
         Validator validator,
         MailSender mailSender) {
       this.validator = validator;
       this.mailSender = mailSender;
  }
Static injection

   protected void configure() {
               bind(Validator.class).to(ValidatorImpl.class);
               requestStaticInjection(OurClass.class);
   }
   …
   …
  @Inject static Validator validator;
Scoping

  protected void configure() {
             bind(Validator.class).to(ValidatorImpl.class)
                   .in(Scopes.SINGLETON);
             bind(MailService.class).to(MailServiceImpl.class)
                   .asEagerSingleton();
  }
Multibindings

  Multibinder<Plugin> pluginBinder =
  Multibinder.newSetBinder(binder(), Plugin.class);
  pluginBinder.addBinding().to(SomePluginImpl.class);
  pluginBinder.addBinding().to(AnotherPluginImpl.class);
  ….

  @Inject Set<Plugin> plugins
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
Advanced Guice
   AOP
   Warp
   Google Gin
   Spring integration
   Using guice with Servlets
Why AOP

   Transaction handling
   Logging
   Security
   Exception handling
   e.t.c
AOP
   void bindInterceptor(
    Match <? super Class<?>> classMatcher,
    Matcher<? super Method> methodMatcher,
    MethodInterceptor... interceptors)


    public interface MethodInterceptor extends
    Interceptor {
        Object invoke (MethodInvocation invocation) throws
        Throwable
    }
AOP

   You can not match on private and final methods
    due to technical limitations in Java
   Only works for objects Guice creates
Warp

   http://www.wideplay.com/
   Eco-system for Google Guice
   Thin lightweight modules for Guice applications
   Persistence
   Transactions
   Servlets
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")
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/
Spring integration

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

   javax.inject
   @Inject
   @Named
   @Qualifier
   @Scope
   @Singleton
   e.t.c
   Supported by Guice, Spring, EJB
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;
Thank you

   Questions ?

Contenu connexe

Tendances

Tendances (16)

Dependency Injection with Unity Container
Dependency Injection with Unity ContainerDependency Injection with Unity Container
Dependency Injection with Unity Container
 
introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basics
 
Dependency Injection Inversion Of Control And Unity
Dependency Injection Inversion Of Control And UnityDependency Injection Inversion Of Control And Unity
Dependency Injection Inversion Of Control And Unity
 
AngularJs presentation
AngularJs presentation AngularJs presentation
AngularJs presentation
 
MongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDBMongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDB
 
Angular interview questions
Angular interview questionsAngular interview questions
Angular interview questions
 
Angular Interview Questions & Answers
Angular Interview Questions & AnswersAngular Interview Questions & Answers
Angular Interview Questions & Answers
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs Workshop
 
Quick answers to Angular2+ Interview Questions
Quick answers to Angular2+ Interview QuestionsQuick answers to Angular2+ Interview Questions
Quick answers to Angular2+ Interview Questions
 
Angular2 + rxjs
Angular2 + rxjsAngular2 + rxjs
Angular2 + rxjs
 
Angular2
Angular2Angular2
Angular2
 
Guice
GuiceGuice
Guice
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Html5 Interview Questions & Answers
Html5 Interview Questions & AnswersHtml5 Interview Questions & Answers
Html5 Interview Questions & Answers
 
Spring MVC Intro / Gore - Nov NHJUG
Spring MVC Intro / Gore - Nov NHJUGSpring MVC Intro / Gore - Nov NHJUG
Spring MVC Intro / Gore - Nov NHJUG
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 

Similaire à Jug Guice Presentation

Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
Ted Pennings
 
Entity framework db model的驗證機制 20130914
Entity framework db model的驗證機制 20130914Entity framework db model的驗證機制 20130914
Entity framework db model的驗證機制 20130914
LearningTech
 
Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejug
robbiev
 
Jasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-casJasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-cas
ellentuck
 
Thomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalThomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-final
Droidcon Berlin
 

Similaire à Jug Guice Presentation (20)

JSRs 303 and 330 in Action
JSRs 303 and 330 in ActionJSRs 303 and 330 in Action
JSRs 303 and 330 in Action
 
Devoxx 2012 (v2)
Devoxx 2012 (v2)Devoxx 2012 (v2)
Devoxx 2012 (v2)
 
Jsr 303
Jsr 303Jsr 303
Jsr 303
 
Sapphire Gimlets
Sapphire GimletsSapphire Gimlets
Sapphire Gimlets
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
 
Guice gin
Guice ginGuice gin
Guice gin
 
Entity framework db model的驗證機制 20130914
Entity framework db model的驗證機制 20130914Entity framework db model的驗證機制 20130914
Entity framework db model的驗證機制 20130914
 
Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejug
 
Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6
 
Creating a Facebook Clone - Part XXV - Transcript.pdf
Creating a Facebook Clone - Part XXV - Transcript.pdfCreating a Facebook Clone - Part XXV - Transcript.pdf
Creating a Facebook Clone - Part XXV - Transcript.pdf
 
Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02
 
Jasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-casJasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-cas
 
CDI @javaonehyderabad
CDI @javaonehyderabadCDI @javaonehyderabad
CDI @javaonehyderabad
 
Thomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalThomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-final
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony Container
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EE
 
ASP.NET MVC 3.0 Validation
ASP.NET MVC 3.0 ValidationASP.NET MVC 3.0 Validation
ASP.NET MVC 3.0 Validation
 
JavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
JavaCro'14 - Building interactive web applications with Vaadin – Peter LehtoJavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
JavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
 
Testing in android
Testing in androidTesting in android
Testing in android
 
Dependency Injection for Android
Dependency Injection for AndroidDependency Injection for Android
Dependency Injection for Android
 

Plus de Dmitry Buzdin

Developing Useful APIs
Developing Useful APIsDeveloping Useful APIs
Developing Useful APIs
Dmitry Buzdin
 
Архитектура Ленты на Одноклассниках
Архитектура Ленты на ОдноклассникахАрхитектура Ленты на Одноклассниках
Архитектура Ленты на Одноклассниках
Dmitry Buzdin
 
Riding Redis @ask.fm
Riding Redis @ask.fmRiding Redis @ask.fm
Riding Redis @ask.fm
Dmitry Buzdin
 
Rubylight JUG Contest Results Part II
Rubylight JUG Contest Results Part IIRubylight JUG Contest Results Part II
Rubylight JUG Contest Results Part II
Dmitry Buzdin
 
Rubylight Pattern-Matching Solutions
Rubylight Pattern-Matching SolutionsRubylight Pattern-Matching Solutions
Rubylight Pattern-Matching Solutions
Dmitry Buzdin
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional Programming
Dmitry Buzdin
 
Rubylight programming contest
Rubylight programming contestRubylight programming contest
Rubylight programming contest
Dmitry Buzdin
 
Continuous Delivery
Continuous Delivery Continuous Delivery
Continuous Delivery
Dmitry Buzdin
 
Introduction to DevOps
Introduction to DevOpsIntroduction to DevOps
Introduction to DevOps
Dmitry Buzdin
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump Analysis
Dmitry Buzdin
 

Plus de Dmitry Buzdin (20)

How Payment Cards Really Work?
How Payment Cards Really Work?How Payment Cards Really Work?
How Payment Cards Really Work?
 
Как построить свой фреймворк для автотестов?
Как построить свой фреймворк для автотестов?Как построить свой фреймворк для автотестов?
Как построить свой фреймворк для автотестов?
 
How to grow your own Microservice?
How to grow your own Microservice?How to grow your own Microservice?
How to grow your own Microservice?
 
How to Build Your Own Test Automation Framework?
How to Build Your Own Test Automation Framework?How to Build Your Own Test Automation Framework?
How to Build Your Own Test Automation Framework?
 
Delivery Pipeline for Windows Machines
Delivery Pipeline for Windows MachinesDelivery Pipeline for Windows Machines
Delivery Pipeline for Windows Machines
 
Big Data Processing Using Hadoop Infrastructure
Big Data Processing Using Hadoop InfrastructureBig Data Processing Using Hadoop Infrastructure
Big Data Processing Using Hadoop Infrastructure
 
JOOQ and Flyway
JOOQ and FlywayJOOQ and Flyway
JOOQ and Flyway
 
Developing Useful APIs
Developing Useful APIsDeveloping Useful APIs
Developing Useful APIs
 
Whats New in Java 8
Whats New in Java 8Whats New in Java 8
Whats New in Java 8
 
Архитектура Ленты на Одноклассниках
Архитектура Ленты на ОдноклассникахАрхитектура Ленты на Одноклассниках
Архитектура Ленты на Одноклассниках
 
Dart Workshop
Dart WorkshopDart Workshop
Dart Workshop
 
Riding Redis @ask.fm
Riding Redis @ask.fmRiding Redis @ask.fm
Riding Redis @ask.fm
 
Rubylight JUG Contest Results Part II
Rubylight JUG Contest Results Part IIRubylight JUG Contest Results Part II
Rubylight JUG Contest Results Part II
 
Rubylight Pattern-Matching Solutions
Rubylight Pattern-Matching SolutionsRubylight Pattern-Matching Solutions
Rubylight Pattern-Matching Solutions
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional Programming
 
Rubylight programming contest
Rubylight programming contestRubylight programming contest
Rubylight programming contest
 
Continuous Delivery
Continuous Delivery Continuous Delivery
Continuous Delivery
 
Introduction to DevOps
Introduction to DevOpsIntroduction to DevOps
Introduction to DevOps
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump Analysis
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 

Jug Guice Presentation

  • 1. Google Guice Kirill Afanasjev Software Architect jug.lv Riga, Latvia
  • 2. Overview  Dependency Injection  Why Guice  Getting Guice  Using Guice  Advanced Guice
  • 3. Code without DI public void sendButtonClicked() { String text = messageArea.getText(); Validator validator = new MailValidator(); validator.validate(text); MailSender sender = new MailSender(); sender.send(text); }
  • 4. Using factories public void sendButtonClicked() { String text = messageArea.getText(); Validator validator = ValidatorFactory.get(); validator.validate(text); MailSender sender = SenderFactory.get(); sender.send(text); }
  • 5. 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(); }
  • 6. 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(); } }
  • 7. Dependency injection private Validator validator; private MailSender mailSender; public MailForm(Validator validator, MailSender mailSender) { this.validator = validator; this.mailSender = mailSender; } public void sendButtonClicked() { …..
  • 8. 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()); }
  • 9. 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
  • 10. What is Guice  Open source dependency injection framework  License : Apache License 2.0  Developer : Google
  • 11. 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)
  • 12. 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
  • 13. Dependency injection with Guice private Validator validator; private MailSender mailSender; @Inject public MailForm(Validator validator, MailSender mailSender) { this.validator = validator; this.mailSender = mailSender; }
  • 14. Creating instance of MailForm Injector injector = Guice.createInjector(new YourAppModule()); MailForm mailForm = injector.getInstance(MailForm.class);
  • 15. Bindings public class YourAppModule extends AbstractModule { protected void configure() { bind(MailService.class).to(MailServiceImpl.class); bind(Validator.class).to(ValidatorImpl.class); } }
  • 16. Providers public class YourAppModule extends AbstractModule { protected void configure() { bind(Validator.class).to(ValidatorImpl.class); } @Provides MailService getMailService() { MailService service = new MailService(); return service; } ….
  • 17. Injecting fields @Inject private Validator validator; @Inject private MailSender mailSender; public MailForm() { }
  • 18. Injecting with setter methods private Validator validator; public MailForm() { } @Inject public void setValidator(Validator validator) { this.validator = validator; }
  • 19. Optional injection  Inject(optional=true)  Ignores values for which no bindings are avalaible  Possible with setter methods only
  • 20. Bind instance protected void configure() { bind(Integer.class).annotatedWith(ThreadCount.cla ss).toInstance(4); } .. @ThreadCount int threadCount;  IDE autocomplete, find usages e.t.c
  • 21. Two implementations protected void configure() { bind(Validator.class).to(ValidatorImpl.class); bind(Validator.class).to(StrictValidatorImpl.class); }
  • 22. 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)
  • 23. 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; }
  • 25. Implicit binding @Inject public MailForm( @ImplementedBy(StrictValidator.class) Validator Validator validator, MailSender mailSender) { this.validator = validator; this.mailSender = mailSender; }
  • 26. Static injection protected void configure() { bind(Validator.class).to(ValidatorImpl.class); requestStaticInjection(OurClass.class); } … … @Inject static Validator validator;
  • 27. Scoping protected void configure() { bind(Validator.class).to(ValidatorImpl.class) .in(Scopes.SINGLETON); bind(MailService.class).to(MailServiceImpl.class) .asEagerSingleton(); }
  • 28. Multibindings Multibinder<Plugin> pluginBinder = Multibinder.newSetBinder(binder(), Plugin.class); pluginBinder.addBinding().to(SomePluginImpl.class); pluginBinder.addBinding().to(AnotherPluginImpl.class); …. @Inject Set<Plugin> plugins
  • 29. 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
  • 30. Advanced Guice  AOP  Warp  Google Gin  Spring integration  Using guice with Servlets
  • 31. Why AOP  Transaction handling  Logging  Security  Exception handling  e.t.c
  • 32. AOP  void bindInterceptor( Match <? super Class<?>> classMatcher, Matcher<? super Method> methodMatcher, MethodInterceptor... interceptors) public interface MethodInterceptor extends Interceptor { Object invoke (MethodInvocation invocation) throws Throwable }
  • 33. AOP  You can not match on private and final methods due to technical limitations in Java  Only works for objects Guice creates
  • 34. Warp  http://www.wideplay.com/  Eco-system for Google Guice  Thin lightweight modules for Guice applications  Persistence  Transactions  Servlets
  • 35. 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")
  • 36. 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/
  • 37. Spring integration  http://code.google.com/p/guice-spring/  @Named(”mySpringBean”)
  • 38. JSR-330  javax.inject  @Inject  @Named  @Qualifier  @Scope  @Singleton  e.t.c  Supported by Guice, Spring, EJB
  • 39. 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;
  • 40. Thank you  Questions ?