guice-servlet

7,025
-1

Published on

guice-servlet

Published in: Technology, News & Politics
2 Comments
10 Likes
Statistics
Notes
No Downloads
Views
Total Views
7,025
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
137
Comments
2
Likes
10
Embeds 0
No embeds

No notes for slide

guice-servlet

  1. 1. guice‐servlet ‐enhanced servlet for Guice‐ May 13th, 2009
  2. 2. introduction Name Masaaki Yonebayashi ID id:yone098 Blog http://d.hatena.ne.jp/yone098/ Company Abby Co.,Ltd.  President
  3. 3. Agenda What is Guice? Feature of Guice Guice Tips Guice with Google App Engine What is guice‐servlet? Feature of guice‐servlet
  4. 4. Guice What is Guice?
  5. 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. 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
  7. 7. Guice Feature of Guice
  8. 8. 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)
  9. 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. 10. Injection setting Module(settings by Java) class SampleModule extends AbstractModule { @Override protected void configure() { bind(Service.class).to(ServiceImpl.class); } }
  11. 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. 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. 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. 14. Guice Scope SINGLETON Scopes.SINGLETON Default Prototype Guice returns a new instance each  time it supplies a value.
  15. 15. Scope setting setting(default scope) class SampleModule extends AbstractModule { @Override protected void configure() { bind(Service.class).to(ServiceImpl.class); } }
  16. 16. Scope setting setting(SINGLETON scope) class SampleModule extends AbstractModule { @Override protected void configure() { bind(Service.class).to(ServiceImpl.class) .in(Scopes.SINGLETON); } }
  17. 17. Scope setting setting(SINGLETON scope) class SampleModule extends AbstractModule { @Override protected void configure() { bind(Service.class).to(ServiceImpl.class) .in(Scopes.SINGLETON); } } demo
  18. 18. Guice break time
  19. 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. 20. Question Choosing Between Implementations public class Person { @Inject private Pet pet; public void runWithPet() { this.pet.run(); } }
  21. 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. 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. 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
  24. 24. Guice solves it
  25. 25. method 1 Using @Named public class Person { @Inject  @Named(“pochi”) private Pet pet; public void runWithPet() { this.pet.run(); } }
  26. 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. 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
  28. 28. Guice another way
  29. 29. method 2 Using Biding Annotation @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER}) @BindingAnnotation public @interface Pochi {}
  30. 30. method 2 Using Biding Annotation public class Person { @Inject  @Pochi private Pet pet; public void runWithPet() { this.pet.run(); } }
  31. 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. 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
  33. 33. Guice Guice Tips
  34. 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. 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. 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. 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
  38. 38. 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.
  39. 39. Summay of Guice All the DI settings can be  described by Java. The injection and scope setting are  easy. Important Module Scope Provider
  40. 40. guice‐servlet What is guice‐servlet?
  41. 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. 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
  43. 43. guice‐servlet Getting Start
  44. 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. 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. 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
  47. 47. guice‐servlet If Java 6 above
  48. 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. 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
  50. 50. guice‐servlet Feature of guice‐servlet
  51. 51. guice‐servlet Annotation @RequestParameters @Inject @RequestParameters private Map<String, String[]> parameters; @RequestScoped @RequestScoped public class SampleAction { } @SessionScoped @SessionScoped public class SampleInfo { } demo
  52. 52. guice‐servlet Session,Request,Response Use @Inject @Inject  private HttpSession session;  @Inject  private ServletRequest request; @Inject  private ServletResponse response;
  53. 53. guice‐servlet Session,Request,Response Use @Inject @Inject  private HttpSession session;  easy! :) @Inject  private ServletRequest request; @Inject  private ServletResponse response;
  54. 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. 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
  56. 56. with Google App Engine Using Guice with Google App Engine
  57. 57. 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.
  58. 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. 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>
  60. 60. with Google App Engine Enjoy! Guice with Google App Engine
  61. 61. Haiku Guice is not juice It’s Guice❤
  62. 62. Thank you! :)
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×