SlideShare a Scribd company logo
1 of 62
Download to read offline
guice‐servlet

 ‐enhanced servlet for Guice‐

               May 13th, 2009
introduction
Name
   Masaaki Yonebayashi
ID
  id:yone098
Blog
  http://d.hatena.ne.jp/yone098/
Company
  Abby Co.,Ltd.  President
Agenda

What is Guice?
 Feature of Guice
 Guice Tips
 Guice with Google App Engine

What is guice‐servlet?
 Feature of guice‐servlet
Guice




What is Guice?
What is Guice?
Guice 1.0 User’s Guide
 Guice is an ultra‐lightweight, next‐
 generation dependency injection 
 container for Java 5 and later.
URL
 http://code.google.com/p/google‐guice/
Project owner
 crazyboblee, kevinb9n, limpbizkit
Release
 2007‐03‐08 1.0 released
Download contents
   Guice 1.0 Download contents
       needs JDK for Java 5 or above
File                     description
guice‐1.0.jar            The core Guice framework
guice‐servlet‐1.0.jar    Web‐related scope addition
guice‐spring‐1.0.jar     Binding Spring beans
guice‐struts2‐plugin‐    Plugin to use Guice as the 
1.0.jar                  DI engine for Struts2
aopalliance.jar          AOP Alliance API, needed to 
                         use Guice AOP
Guice




Feature of Guice
Feature of Guice


All the DI settings can be 
described by Java.
The injection and scope setting are 
easy.
The unit test is easy.
Results(Google Adwords)
Injection style
    Guice Injection styles
Injection  Locaion     example
order
           Constructor public class    Ex {
1
                             @Inject
                             public Ex(AaService aaService){…}
                         }
                         @Inject
2          Field
                         private BbService bbService;
                         @Inject
3          Setter
                         public void setCcService(
                             CcService ccService){…}
Injection setting
   Module(settings by Java)
class SampleModule extends AbstractModule {
  @Override
  protected void configure() {
    bind(Service.class).to(ServiceImpl.class);
  }
}
Injection setting
   Module(settings by Java)
class SampleModule extends AbstractModule {
  @Override

If you don’t set it
  protected void configure() {
    bind(Service.class).to(ServiceImpl.class);
  }
}
Injection setting
   ConfigurationException :(
com.google.inject.ConfigurationException: 
  Error at 
  samples.Client.<init>(Client.java:20) 
  Binding to samples.Service not found. 
  No bindings to that type were found.
Injection setting
   ConfigurationException :(
com.google.inject.ConfigurationException: 
  Error at 
  samples.Client.<init>(Client.java:20) 
  Binding to samples.Service not found. 
  No bindings to that type were found.


                                 demo
Guice Scope

SINGLETON
 Scopes.SINGLETON
Default
 Prototype
  Guice returns a new instance each 
  time it supplies a value.
Scope setting
   setting(default scope)
class SampleModule extends AbstractModule {
  @Override
  protected void configure() {
    bind(Service.class).to(ServiceImpl.class);
  }
}
Scope setting
   setting(SINGLETON scope)
class SampleModule extends AbstractModule {
  @Override
  protected void configure() {
    bind(Service.class).to(ServiceImpl.class)
        .in(Scopes.SINGLETON);
  }
}
Scope setting
   setting(SINGLETON scope)
class SampleModule extends AbstractModule {
  @Override
  protected void configure() {
    bind(Service.class).to(ServiceImpl.class)
        .in(Scopes.SINGLETON);
  }
}


                                    demo
Guice




break time
Question
      Choosing Between Implementations
                          public interface Pet {
                            String name();
                            void run();
                          }


public class Cat implements Pet {       public class Dog implements Pet {
  public String name() {                  public String name() {
    return quot;Catquot;;                           return “Dogquot;;
  }                                       }
  public void run() {                     public void run() {
    System.out.println(quot;Cat is runquot;);       System.out.println(“Dog is runquot;);
  }                                       }
}                                       }
Question
Choosing Between Implementations

    public class Person {
     @Inject
      private Pet pet;

        public void runWithPet() {
          this.pet.run();
        }
    }
Question
    Choosing Between Implementations
Public static void main(String[] args) {
  Injector injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
      bind(Pet.class).to(Dog.class);
      bind(Pet.class).to(Cat.class);
    }
  });
  Person person = injector.getInstance(Person.class);
  person.runWithPet();
}
Answer
    CreationException :(
Exception in thread quot;mainquot; 
  com.google.inject.CreationException: Guice configuration 
  errors:

1) Error at 
  samples.GuicePetSample$1.configure(GuicePetSample.java:16
  ):
 A binding to samples.Pet was already configured at 
  samples.GuicePetSample$1.configure(GuicePetSample.java:15
  ).
Answer
    CreationException :(
Exception in thread quot;mainquot; 
  com.google.inject.CreationException: Guice configuration 
  errors:

1) Error at 
  samples.GuicePetSample$1.configure(GuicePetSample.java:16
  ):
 A binding to samples.Pet was already configured at 
  samples.GuicePetSample$1.configure(GuicePetSample.java:15
  ).



                                            demo
Guice




solves it
method 1
Using @Named
   public class Person {
     @Inject 
     @Named(“pochi”)
     private Pet pet;

       public void runWithPet() {
         this.pet.run();
       }
   }
method 1
    Using @Named
Public static void main(String[] args) {
  Injector injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
      bind(Pet.class).annotatedWith(Names.name(“pochi”))
          .to(Dog.class);
      bind(Pet.class).to(Cat.class);
    }
  });
  Person person = injector.getInstance(Person.class);
  person.runWithPet();
}
method 1
    Using @Named
Public static void main(String[] args) {
  Injector injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
      bind(Pet.class).annotatedWith(Names.name(“pochi”))
          .to(Dog.class);
      bind(Pet.class).to(Cat.class);
    }
  });
  Person person = injector.getInstance(Person.class);
  person.runWithPet();
}


                                                 demo
Guice




another way
method 2
Using Biding Annotation
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,
              ElementType.PARAMETER})
@BindingAnnotation
public @interface Pochi {}
method 2
Using Biding Annotation
   public class Person {
     @Inject 
     @Pochi
     private Pet pet;

       public void runWithPet() {
         this.pet.run();
       }
   }
method 2
    Using Biding Annotation
Public static void main(String[] args) {
  Injector injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
      bind(Pet.class).annotatedWith(Pochi.class)
          .to(Dog.class);
      bind(Pet.class).to(Cat.class);
    }
  });
  Person person = injector.getInstance(Person.class);
  person.runWithPet();
}
method 2
    Using Biding Annotation
Public static void main(String[] args) {
  Injector injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
      bind(Pet.class).annotatedWith(Pochi.class)
          .to(Dog.class);
      bind(Pet.class).to(Cat.class);
    }
  });
  Person person = injector.getInstance(Person.class);
  person.runWithPet();
}


                                                 demo
Guice




Guice Tips
Guice Tips
     Debug Logging, create class
public class GuiceDebug {
  private static final Handler HANDLER = new ConsoleHandler() {{
    setLevel(Level.ALL); setFormatter(new Formatter() {
      public String format(LogRecord r) {
        return String.format(“[Debug Guice] %s%nquot;, r.getMessage());
      }
    });
  }};
  private GuiceDebug() {}
  public static void enable() {
    Logger guiceLogger = Logger.getLogger(quot;com.google.injectquot;);
    guiceLogger.addHandler(GuiceDebug.HANDLER);
    guiceLogger.setLevel(Level.ALL);
  }
}
Guice Tips
    Using GuiceDebug
Public static void main(String[] args) {
  GuiceDebug.enable();
  Injector injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
      bind(Pet.class).to(Cat.class);
    }
  });
  Person person = injector.getInstance(Person.class);
  person.runWithPet();
}
Guice Tips
   console
[Debug Guice] Configuration: 32ms
[Debug Guice] Binding creation: 47ms
[Debug Guice] Binding indexing: 0ms
[Debug Guice] Validation: 109ms
[Debug Guice] Static validation: 0ms
[Debug Guice] Static member injection: 0ms
[Debug Guice] Instance injection: 0ms
[Debug Guice] Preloading: 0ms
Guice Tips
   console
[Debug Guice] Configuration: 32ms
[Debug Guice] Binding creation: 47ms
[Debug Guice] Binding indexing: 0ms
[Debug Guice] Validation: 109ms
[Debug Guice] Static validation: 0ms
[Debug Guice] Static member injection: 0ms
[Debug Guice] Instance injection: 0ms
[Debug Guice] Preloading: 0ms



                                       demo
Other Tips


Integrating with the Spring 
Framework.
Using JNDI with Guice.
Using JMX.
 Guice has built‐in support to inspect an 
 Injector's bindings at runtime using the 
 JMX.
Summay of Guice

All the DI settings can be 
described by Java.
The injection and scope setting are 
easy.
Important
 Module
 Scope
 Provider
guice‐servlet



What is guice‐servlet?
What is guice‐servlet?
guice‐servlet 1.0
 Meaning that your servlets and filters 
 benefit from:
   Constructor injection 
   Type‐safe, idiomatic configuration 
   Modularization
   Guice AOP
What is guice‐servlet?
guice‐servlet 1.0
 It's very simple, because they are only 
 6 files.
   GuiceFilter
   RequestParameters
   RequestScoped
   ServletModule
   ServletScopes
   SessionScoped
guice‐servlet




Getting Start
Getting Start
   web.xml
<filter>
  <filter‐name>guiceFilter</filter‐name>
  <filter‐class>
    com.google.inject.servlet.GuiceFilter
  </filter‐class>
</filter>
<filter‐mapping>
  <filter‐name>guiceFilter</filter‐name>
  <url‐pattern>/*</url‐pattern>
</filter‐mapping>
Getting Start
     Install ServletModule
public class GuiceServletListener 
         implements ServletContextListener {
 protected Injector getInjector() {
   return Guice.createInjector(new ServletModule());
 }
  public void contextInitialize(ServletContext sce) { // setAttribute }
 public void contextDestroyed(ServletContextEvent sce) { // removeAttribute }
}


     web.xml
<listener>
 <listener‐class>example.GuiceServletListener</listener‐class>
</listener>
Getting Start
     Install ServletModule
public class GuiceServletListener 
         implements ServletContextListener {
 protected Injector getInjector() {
   return Guice.createInjector(new ServletModule());
 }
  public void contextInitialize(ServletContext sce) { // setAttribute }
 public void contextDestroyed(ServletContextEvent sce) { // removeAttribute }
}


     web.xml
<listener>
 <listener‐class>example.GuiceServletListener</listener‐class>
</listener>

                                       see Sample code
guice‐servlet




If Java 6 above
Guice Tips
    Using ServiceLoader
        META‐INF/services/com.google.inject.Module
example.ApplicationModule
        ApplicationModule.java
public class ApplicationModule extends AbstractModule {
  @Override
  protected void configure() {
    install(new ServletModule());
  }
}

ServiceLoader<com.google.inject.Module> module =
    ServiceLoader.load(com.google.inject.Module.class);
Injector injector = Guice.createInjector(modules);
Guice Tips
    Using ServiceLoader
        META‐INF/services/com.google.inject.Module
example.ApplicationModule
        ApplicationModule.java
public class ApplicationModule extends AbstractModule {
  @Override
  protected void configure() {
    install(new ServletModule());
  }
}

ServiceLoader<com.google.inject.Module> module =
    ServiceLoader.load(com.google.inject.Module.class);
Injector injector = Guice.createInjector(modules);

                                                          demo
guice‐servlet



Feature of guice‐servlet
guice‐servlet
    Annotation
      @RequestParameters
@Inject
@RequestParameters
private Map<String, String[]> parameters;
      @RequestScoped
@RequestScoped
public class SampleAction {
}
      @SessionScoped
@SessionScoped
public class SampleInfo {
}

                                                 demo
guice‐servlet
   Session,Request,Response
     Use @Inject
@Inject 
private HttpSession session; 

@Inject 
private ServletRequest request;

@Inject 
private ServletResponse response;
guice‐servlet
   Session,Request,Response
     Use @Inject
@Inject 
private HttpSession session; 



           easy! :)
@Inject 
private ServletRequest request;

@Inject 
private ServletResponse response;
guice‐servlet
    Session,Request,Response
      Use Injector
@Inject private Injector injector;

HttpSession session = injector.getInstance(HttpSession.class);

ServletRequest request = injector.getInstance(ServletRequest.class);
HttpServletRequest request2 = 
         injector.getInstance(HttpServletRequest.class);

ServletResponse response =
        injector.getInstance(ServletResponse.class);
HttpServletResponse response2 =
        injector.getInstance(HttpServletResponse.class);
guice‐servlet
    Session,Request,Response
      Use Injector
@Inject private Injector injector;

HttpSession session = injector.getInstance(HttpSession.class);

ServletRequest request = injector.getInstance(ServletRequest.class);
HttpServletRequest request2 = 
         injector.getInstance(HttpServletRequest.class);

ServletResponse response =
        injector.getInstance(ServletResponse.class);
HttpServletResponse response2 =
        injector.getInstance(HttpServletResponse.class);

                                                             demo
with Google App Engine



Using Guice
with Google App Engine
with Google App Engine


Guice 1.0 is not supported :(
GAE support was added in rev#937.
 http://code.google.com/p/google‐guice/source/detail?r=937

It requires Guice 2 (with or 
without AOP), plus the guice‐
servlet extension.
with GAE setup
     Servlet and Filter Registration
class MyServletModule extends com.google.inject.servlet.ServletModule { 
  @Override
  protected void configureServlets() {
    serve(“/*”).with(MyServlet.class);
  }
}

     Injector Creation
public class MyGuiceServletContextListener 
          extends com.google.inject.servlet.GuiceServletContextListener { 
  @Override protected Injector getInjector() {
    return Guice.createInjector(new MyServletModule());
  }
}
with GAE setup
    web.xml configration
<filter>
  <filter‐name>guiceFilter</filter‐name>
  <filter‐class>com.google.inject.servlet.GuiceFilter</filter‐class>
</filter>
<filter‐mapping>
  <filter‐name>guiceFilter</filter‐name>
  <url‐pattern>/*</url‐pattern>
</filter‐mapping>
<listener>
  <listener‐class>
    example.MyGuiceServletContextListener
  </listener‐class>
</listener>
with Google App Engine



Enjoy! Guice
with Google App Engine
Haiku


Guice is
not juice
It’s Guice❤
Thank you!
    :)

More Related Content

What's hot

Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6
Ray Ploski
 

What's hot (20)

Under the Hood: Using Spring in Grails
Under the Hood: Using Spring in GrailsUnder the Hood: Using Spring in Grails
Under the Hood: Using Spring in Grails
 
Under the Hood: Using Spring in Grails
Under the Hood: Using Spring in GrailsUnder the Hood: Using Spring in Grails
Under the Hood: Using Spring in Grails
 
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
 
Mpg Dec07 Gian Lorenzetto
Mpg Dec07 Gian Lorenzetto Mpg Dec07 Gian Lorenzetto
Mpg Dec07 Gian Lorenzetto
 
T.Y.B.S.CS Advance Java Practicals Sem 5 Mumbai University
T.Y.B.S.CS Advance Java Practicals Sem 5 Mumbai UniversityT.Y.B.S.CS Advance Java Practicals Sem 5 Mumbai University
T.Y.B.S.CS Advance Java Practicals Sem 5 Mumbai University
 
What's new in Android O
What's new in Android OWhat's new in Android O
What's new in Android O
 
Nativescript angular
Nativescript angularNativescript angular
Nativescript angular
 
Demystifying dependency Injection: Dagger and Toothpick
Demystifying dependency Injection: Dagger and ToothpickDemystifying dependency Injection: Dagger and Toothpick
Demystifying dependency Injection: Dagger and Toothpick
 
AJUG April 2011 Cascading example
AJUG April 2011 Cascading exampleAJUG April 2011 Cascading example
AJUG April 2011 Cascading example
 
Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6
 
The secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you aboutThe secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you about
 
Тестирование на Android с Dagger 2
Тестирование на Android с Dagger 2Тестирование на Android с Dagger 2
Тестирование на Android с Dagger 2
 
Graphql, REST and Apollo
Graphql, REST and ApolloGraphql, REST and Apollo
Graphql, REST and Apollo
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42
 
Dependency Injection with CDI in 15 minutes
Dependency Injection with CDI in 15 minutesDependency Injection with CDI in 15 minutes
Dependency Injection with CDI in 15 minutes
 
Grid gain paper
Grid gain paperGrid gain paper
Grid gain paper
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Writing and using Hamcrest Matchers
Writing and using Hamcrest MatchersWriting and using Hamcrest Matchers
Writing and using Hamcrest Matchers
 
Zenddispatch en
Zenddispatch enZenddispatch en
Zenddispatch en
 
Easy REST APIs with Jersey and RestyGWT
Easy REST APIs with Jersey and RestyGWTEasy REST APIs with Jersey and RestyGWT
Easy REST APIs with Jersey and RestyGWT
 

Similar to guice-servlet

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
 
Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice Presentation
Dmitry Buzdin
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
Darwin Durand
 

Similar to guice-servlet (20)

Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Sapphire Gimlets
Sapphire GimletsSapphire Gimlets
Sapphire Gimlets
 
Guice gin
Guice ginGuice gin
Guice gin
 
Unit testing with mock libs
Unit testing with mock libsUnit testing with mock libs
Unit testing with mock libs
 
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
 
Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"
 
Svcc Groovy Testing
Svcc Groovy TestingSvcc Groovy Testing
Svcc Groovy Testing
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice Presentation
 
JSUG - Google Guice by Jan Zarnikov
JSUG - Google Guice by Jan ZarnikovJSUG - Google Guice by Jan Zarnikov
JSUG - Google Guice by Jan Zarnikov
 
Testing in android
Testing in androidTesting in android
Testing in android
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
 
Greach, GroovyFx Workshop
Greach, GroovyFx WorkshopGreach, GroovyFx Workshop
Greach, GroovyFx Workshop
 
Dependency Injection for Android
Dependency Injection for AndroidDependency Injection for Android
Dependency Injection for Android
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
 
Jersey Guice AOP
Jersey Guice AOPJersey Guice AOP
Jersey Guice AOP
 
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
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
So how do I test my Sling application?
 So how do I test my Sling application? So how do I test my Sling application?
So how do I test my Sling application?
 

More from Masaaki Yonebayashi (14)

Go guide for Java programmer
Go guide for Java programmerGo guide for Java programmer
Go guide for Java programmer
 
HHVM Hack
HHVM HackHHVM Hack
HHVM Hack
 
Android T2 on cloud
Android T2 on cloudAndroid T2 on cloud
Android T2 on cloud
 
JavaFX-with-Adobe
JavaFX-with-AdobeJavaFX-with-Adobe
JavaFX-with-Adobe
 
Flex's DI Container
Flex's DI ContainerFlex's DI Container
Flex's DI Container
 
T2 in Action
T2 in ActionT2 in Action
T2 in Action
 
T2@java-ja#toyama
T2@java-ja#toyamaT2@java-ja#toyama
T2@java-ja#toyama
 
Merapi -Adobe Air<=>Java-
Merapi -Adobe Air<=>Java-Merapi -Adobe Air<=>Java-
Merapi -Adobe Air<=>Java-
 
sc2009white_T2
sc2009white_T2sc2009white_T2
sc2009white_T2
 
sc2009white_Teeda
sc2009white_Teedasc2009white_Teeda
sc2009white_Teeda
 
yonex
yonexyonex
yonex
 
S2Flex2
S2Flex2S2Flex2
S2Flex2
 
Teeda
TeedaTeeda
Teeda
 
Wankumatoyama#01
Wankumatoyama#01Wankumatoyama#01
Wankumatoyama#01
 

Recently uploaded

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

guice-servlet

  • 2. introduction Name Masaaki Yonebayashi ID id:yone098 Blog http://d.hatena.ne.jp/yone098/ Company Abby Co.,Ltd.  President
  • 3. Agenda What is Guice? Feature of Guice Guice Tips Guice with Google App Engine What is guice‐servlet? Feature of guice‐servlet
  • 5. What is Guice? Guice 1.0 User’s Guide Guice is an ultra‐lightweight, next‐ generation dependency injection  container for Java 5 and later. URL http://code.google.com/p/google‐guice/ Project owner crazyboblee, kevinb9n, limpbizkit Release 2007‐03‐08 1.0 released
  • 6. Download contents Guice 1.0 Download contents needs JDK for Java 5 or above File description guice‐1.0.jar The core Guice framework guice‐servlet‐1.0.jar Web‐related scope addition guice‐spring‐1.0.jar Binding Spring beans guice‐struts2‐plugin‐ Plugin to use Guice as the  1.0.jar DI engine for Struts2 aopalliance.jar AOP Alliance API, needed to  use Guice AOP
  • 9. Injection style Guice Injection styles Injection  Locaion example order Constructor public class Ex { 1 @Inject public Ex(AaService aaService){…} } @Inject 2 Field private BbService bbService; @Inject 3 Setter public void setCcService( CcService ccService){…}
  • 10. Injection setting Module(settings by Java) class SampleModule extends AbstractModule { @Override protected void configure() { bind(Service.class).to(ServiceImpl.class); } }
  • 11. Injection setting Module(settings by Java) class SampleModule extends AbstractModule { @Override If you don’t set it protected void configure() { bind(Service.class).to(ServiceImpl.class); } }
  • 12. Injection setting ConfigurationException :( com.google.inject.ConfigurationException:  Error at  samples.Client.<init>(Client.java:20)  Binding to samples.Service not found.  No bindings to that type were found.
  • 13. Injection setting ConfigurationException :( com.google.inject.ConfigurationException:  Error at  samples.Client.<init>(Client.java:20)  Binding to samples.Service not found.  No bindings to that type were found. demo
  • 14. Guice Scope SINGLETON Scopes.SINGLETON Default Prototype Guice returns a new instance each  time it supplies a value.
  • 15. Scope setting setting(default scope) class SampleModule extends AbstractModule { @Override protected void configure() { bind(Service.class).to(ServiceImpl.class); } }
  • 16. Scope setting setting(SINGLETON scope) class SampleModule extends AbstractModule { @Override protected void configure() { bind(Service.class).to(ServiceImpl.class) .in(Scopes.SINGLETON); } }
  • 17. Scope setting setting(SINGLETON scope) class SampleModule extends AbstractModule { @Override protected void configure() { bind(Service.class).to(ServiceImpl.class) .in(Scopes.SINGLETON); } } demo
  • 19. Question Choosing Between Implementations public interface Pet { String name(); void run(); } public class Cat implements Pet { public class Dog implements Pet { public String name() { public String name() { return quot;Catquot;; return “Dogquot;; } } public void run() { public void run() { System.out.println(quot;Cat is runquot;); System.out.println(“Dog is runquot;); } } } }
  • 20. Question Choosing Between Implementations public class Person { @Inject private Pet pet; public void runWithPet() { this.pet.run(); } }
  • 21. Question Choosing Between Implementations Public static void main(String[] args) { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(Pet.class).to(Dog.class); bind(Pet.class).to(Cat.class); } }); Person person = injector.getInstance(Person.class); person.runWithPet(); }
  • 22. Answer CreationException :( Exception in thread quot;mainquot;  com.google.inject.CreationException: Guice configuration  errors: 1) Error at  samples.GuicePetSample$1.configure(GuicePetSample.java:16 ): A binding to samples.Pet was already configured at  samples.GuicePetSample$1.configure(GuicePetSample.java:15 ).
  • 23. Answer CreationException :( Exception in thread quot;mainquot;  com.google.inject.CreationException: Guice configuration  errors: 1) Error at  samples.GuicePetSample$1.configure(GuicePetSample.java:16 ): A binding to samples.Pet was already configured at  samples.GuicePetSample$1.configure(GuicePetSample.java:15 ). demo
  • 25. method 1 Using @Named public class Person { @Inject  @Named(“pochi”) private Pet pet; public void runWithPet() { this.pet.run(); } }
  • 26. method 1 Using @Named Public static void main(String[] args) { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(Pet.class).annotatedWith(Names.name(“pochi”)) .to(Dog.class); bind(Pet.class).to(Cat.class); } }); Person person = injector.getInstance(Person.class); person.runWithPet(); }
  • 27. method 1 Using @Named Public static void main(String[] args) { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(Pet.class).annotatedWith(Names.name(“pochi”)) .to(Dog.class); bind(Pet.class).to(Cat.class); } }); Person person = injector.getInstance(Person.class); person.runWithPet(); } demo
  • 29. method 2 Using Biding Annotation @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER}) @BindingAnnotation public @interface Pochi {}
  • 30. method 2 Using Biding Annotation public class Person { @Inject  @Pochi private Pet pet; public void runWithPet() { this.pet.run(); } }
  • 31. method 2 Using Biding Annotation Public static void main(String[] args) { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(Pet.class).annotatedWith(Pochi.class) .to(Dog.class); bind(Pet.class).to(Cat.class); } }); Person person = injector.getInstance(Person.class); person.runWithPet(); }
  • 32. method 2 Using Biding Annotation Public static void main(String[] args) { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(Pet.class).annotatedWith(Pochi.class) .to(Dog.class); bind(Pet.class).to(Cat.class); } }); Person person = injector.getInstance(Person.class); person.runWithPet(); } demo
  • 34. Guice Tips Debug Logging, create class public class GuiceDebug { private static final Handler HANDLER = new ConsoleHandler() {{ setLevel(Level.ALL); setFormatter(new Formatter() { public String format(LogRecord r) { return String.format(“[Debug Guice] %s%nquot;, r.getMessage()); } }); }}; private GuiceDebug() {} public static void enable() { Logger guiceLogger = Logger.getLogger(quot;com.google.injectquot;); guiceLogger.addHandler(GuiceDebug.HANDLER); guiceLogger.setLevel(Level.ALL); } }
  • 35. Guice Tips Using GuiceDebug Public static void main(String[] args) { GuiceDebug.enable(); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(Pet.class).to(Cat.class); } }); Person person = injector.getInstance(Person.class); person.runWithPet(); }
  • 36. Guice Tips console [Debug Guice] Configuration: 32ms [Debug Guice] Binding creation: 47ms [Debug Guice] Binding indexing: 0ms [Debug Guice] Validation: 109ms [Debug Guice] Static validation: 0ms [Debug Guice] Static member injection: 0ms [Debug Guice] Instance injection: 0ms [Debug Guice] Preloading: 0ms
  • 37. Guice Tips console [Debug Guice] Configuration: 32ms [Debug Guice] Binding creation: 47ms [Debug Guice] Binding indexing: 0ms [Debug Guice] Validation: 109ms [Debug Guice] Static validation: 0ms [Debug Guice] Static member injection: 0ms [Debug Guice] Instance injection: 0ms [Debug Guice] Preloading: 0ms demo
  • 41. What is guice‐servlet? guice‐servlet 1.0 Meaning that your servlets and filters  benefit from: Constructor injection  Type‐safe, idiomatic configuration  Modularization Guice AOP
  • 42. What is guice‐servlet? guice‐servlet 1.0 It's very simple, because they are only  6 files. GuiceFilter RequestParameters RequestScoped ServletModule ServletScopes SessionScoped
  • 44. Getting Start web.xml <filter> <filter‐name>guiceFilter</filter‐name> <filter‐class> com.google.inject.servlet.GuiceFilter </filter‐class> </filter> <filter‐mapping> <filter‐name>guiceFilter</filter‐name> <url‐pattern>/*</url‐pattern> </filter‐mapping>
  • 45. Getting Start Install ServletModule public class GuiceServletListener  implements ServletContextListener { protected Injector getInjector() { return Guice.createInjector(new ServletModule()); } public void contextInitialize(ServletContext sce) { // setAttribute } public void contextDestroyed(ServletContextEvent sce) { // removeAttribute } } web.xml <listener> <listener‐class>example.GuiceServletListener</listener‐class> </listener>
  • 46. Getting Start Install ServletModule public class GuiceServletListener  implements ServletContextListener { protected Injector getInjector() { return Guice.createInjector(new ServletModule()); } public void contextInitialize(ServletContext sce) { // setAttribute } public void contextDestroyed(ServletContextEvent sce) { // removeAttribute } } web.xml <listener> <listener‐class>example.GuiceServletListener</listener‐class> </listener> see Sample code
  • 48. Guice Tips Using ServiceLoader META‐INF/services/com.google.inject.Module example.ApplicationModule ApplicationModule.java public class ApplicationModule extends AbstractModule { @Override protected void configure() { install(new ServletModule()); } } ServiceLoader<com.google.inject.Module> module = ServiceLoader.load(com.google.inject.Module.class); Injector injector = Guice.createInjector(modules);
  • 49. Guice Tips Using ServiceLoader META‐INF/services/com.google.inject.Module example.ApplicationModule ApplicationModule.java public class ApplicationModule extends AbstractModule { @Override protected void configure() { install(new ServletModule()); } } ServiceLoader<com.google.inject.Module> module = ServiceLoader.load(com.google.inject.Module.class); Injector injector = Guice.createInjector(modules); demo
  • 51. guice‐servlet Annotation @RequestParameters @Inject @RequestParameters private Map<String, String[]> parameters; @RequestScoped @RequestScoped public class SampleAction { } @SessionScoped @SessionScoped public class SampleInfo { } demo
  • 52. guice‐servlet Session,Request,Response Use @Inject @Inject  private HttpSession session;  @Inject  private ServletRequest request; @Inject  private ServletResponse response;
  • 53. guice‐servlet Session,Request,Response Use @Inject @Inject  private HttpSession session;  easy! :) @Inject  private ServletRequest request; @Inject  private ServletResponse response;
  • 54. guice‐servlet Session,Request,Response Use Injector @Inject private Injector injector; HttpSession session = injector.getInstance(HttpSession.class); ServletRequest request = injector.getInstance(ServletRequest.class); HttpServletRequest request2 =  injector.getInstance(HttpServletRequest.class); ServletResponse response = injector.getInstance(ServletResponse.class); HttpServletResponse response2 = injector.getInstance(HttpServletResponse.class);
  • 55. guice‐servlet Session,Request,Response Use Injector @Inject private Injector injector; HttpSession session = injector.getInstance(HttpSession.class); ServletRequest request = injector.getInstance(ServletRequest.class); HttpServletRequest request2 =  injector.getInstance(HttpServletRequest.class); ServletResponse response = injector.getInstance(ServletResponse.class); HttpServletResponse response2 = injector.getInstance(HttpServletResponse.class); demo
  • 58. with GAE setup Servlet and Filter Registration class MyServletModule extends com.google.inject.servlet.ServletModule {  @Override protected void configureServlets() { serve(“/*”).with(MyServlet.class); } } Injector Creation public class MyGuiceServletContextListener  extends com.google.inject.servlet.GuiceServletContextListener {  @Override protected Injector getInjector() { return Guice.createInjector(new MyServletModule()); } }
  • 59. with GAE setup web.xml configration <filter> <filter‐name>guiceFilter</filter‐name> <filter‐class>com.google.inject.servlet.GuiceFilter</filter‐class> </filter> <filter‐mapping> <filter‐name>guiceFilter</filter‐name> <url‐pattern>/*</url‐pattern> </filter‐mapping> <listener> <listener‐class> example.MyGuiceServletContextListener </listener‐class> </listener>