SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Sapphire Gimlets*  Robert Cooper ReachCall.com *no onions
Guice Dependency Injection Java Source configuration Convention over configuration Fast
Gin Guice for GWT apps 100% Client Side Based on Deferred Binding, so some limitations Fast
Guicevs Spring Spring Config Hell Promise of simplicity Ever expanding config files Lots of subprojects Becomes more brittle, in that it becomes harder to extract code for reuse.
Guicevs Spring Guice Java Source “configuration” Convention over configuration. Annotation based Opposite of Spring in defaults Prefer constructor injection Prefer new instances (“Prototype”) over Singletons Provider<T> interface encourages mixing scopes Type Safe – you got static typing, use it!
Guice 101 Basic Annotations @Inject @ImplementedBy/@ProvidedBy @[Scope] @Named
Guice 101 public class MyClass {     private final MyService service;     @Injectpublic MyClass(finalMyService service){this.service = service;}     public String sayHelloToUser(){	return this.service.hello();} }    @ImplementedBy(MyServiceImpl.class)public interface MyService {     public String hello();}
Guice 101 @Singleton public class MyServiceImpl implements MyService {     private final Provider<MySessionObject> sessionProvider;     public MyServiceImpl(final Provider<MySessionObject> sessionProvider){ this.sessionProvider = sessionProvider;     }     @Override     public String hello() {         return "Hello, "+sessionProvider.get().getName() +"!";     } }
Guice 101 import com.google.inject.servlet.SessionScoped; @SessionScoped public class MySessionObject {     private String name;     public String getName(){         return this.name;     }     public void setName(String name){ this.name = name;     } }
Guice 101 What have we done? MyClass gets a MyService injected. MyService is implemented by MyServiceImpl as a Singleton MyServiceImpl gets a Provider<MySessionObject> The hello() method fetches the Session scoped MySession object, and says Hello!
Guice 101 @ImplementedBy provides defaults for any interface (You don’t need to config these if the default is OK) Injection is type safe on constructors (Unit tests have obvious requirements) Scope annotations (@SessionScoped, @Singleton) provide defaults. Provider<T> hides the scope shift from the Singleton service in a single thread method.
Guice 101 Making it work on the web…
Guice 101 public class GuiceContextListener extends GuiceServletContextListener {     @Override     protected Injector getInjector() {         return Guice.createInjector(             new Module() {                public void configure(Binder binder) {                   // Oh Wait, we don’t need anything here!                 }             }          }, new ServletModule() {                 @Override                 protected void configureServlets() { this.serve(“/myPath/*”).with(MyServlet.class);                 }           }     } }
Guice 101 Warning! Overly complicated coming up!
Guice 101 @Singleton public class MyServlet extends HttpServlet{     private final Provider<MySessionObject> sessionProvider;     private final MyClassmyClass;     @Inject     public MyServlet(final Provider<MySessionObject> sessionProvider, MyClassmyClass){ this.sessionProvider = sessionProvider; this.myClass = myClass;     }     @Override     public void doGet(HttpServletRequestreq, HttpServletResponse res) throws IOException { this.sessionProvider.get().setName(req.getParameter("name")); res.getWriter().println(myClass.hello());     } }
Guice 101 So this is interesting. What happened there? The SessionScoped object was created, and set on the session. MyClass was created one off for injection into the servlet. Since it wasn’t a Provider<MyClass> it was implicitly @Singleton with the servlet But since the MyClass implementation used a provider, it ended up performing a singleton-session scoped op.
Guice 101 What else? Servlets, Filters, etc must always be @Singleton of course, this just makes sense. They can *still* get anything injected into them. You need to add your boostrapGuiceContextListener to your web.xml For Servlet < 3.0 you need to add a com.google.inject.servlet.GuiceFilter to /*
Guice 201 Why does this rock? (Hint GWT stuff…)  Can you say RemoteServiceServlet? No more calls to getThreadLocalX() for servlet context stuff. Just use Provider<T>
Guice 201: Warp The Warp-* projects provide a lot of utility ops for Guice: @Transactional scope Transaction per Request Some stuff not dissimilar to Spring WebFlow or Stripes.
Guice 201: More Config @Named lets you provide named values in your configuration. (You can also create custom annotations) You can also use @Provides for factory methods in your modules for simple providers @Provides  public Connection getConnection(@Named(“jdbc-url”) String jdbcUrl) { DriverManager.forName(whatever); DriverManager.getConnection(jdbcUrl); }
Guice 201: More Config binder.bind(String.class).annotatedWith(Names.named(“jdbc-url”)).toInstance(“jdbc:mysql://localhost/mydb”); Note: @Provides methods could do JNDI lookups, or get other stuff. (This is a stupid example!)
Of Junipers and Bathtubs Gin is Google Guice for GWT client side apps. Based on DeferrredBinding. Certain features lost: Binding .toInstance() on any module Anonymous Provider<T> can’t be done (@Provides is *kinda* OK) Scoping needs to be by hard class reference.
Of Junipers and Bathtubs That is.. in(Singleton.class) not .asEagerSingleton() or with @Singleton Gin seems both stupid and too smart. Binding a RemoteServiceAsync class works out of the box… Unless you want to do @Provides Gin created classes are new Class() not GWT.create(Class.class); -- except for RemoteServiceAsync, which is a special scope.
Gin 101 @GinModules(MyGinModule.class) public interface Injector extends Ginjector {     public static final Injector INSTANCE = GWT.create(Injector.class);     public MyStartupClassstartupClass(); } public classMyGinModuleextends AbstractGinModule {     @Override     protected void configure() { this.bind(Resources.class)             .toProvider(ResourcesProvider.class)             .in(Singleton.class)     } } public static class ResourcesProvider implements Provider<Resources> {      @Override      public Resources get() {             return GWT.create(Resources.class);      } }
Gin 101 Does this step on the toes of DeBi?  OK, maybe a little bit. Sure you could do a singleton Resources.INSTANCE but injection makes Unit testing without dropping into GWTTestCase more frequent. (Read: much, much faster) This reserves DeBi for what it is best for: local environment specific code.
Gin 201 What can’t you do with Gin? Remember your Injector.INSTANCE is compile-time: No “toInstance()” bindings… ever. No “toProvider(AnonymousProvider(){})” providers need to be public scoped static classes at the least. Gin treats RemoteServiceAsync specially. You can do a provider, but if you try @Provides methods in your GinModule classes, you will get a duplicate declaration error.
Gin 201 All this aside, stacked with DeBi, Gin can rock rough and stuff with its Afro Puffs. Replace your Startup call with a Sync method. Replace your Async classes with thing that talk to local storage. Automagically retry onFailure() methods on network errors while your uses if offline.
Way way more Warp-* is some great stuff: http://code.google.com/p/warp-persist/ http://code.google.com/p/google-sitebricks/ Guice with JAX-WShttps://jax-ws-commons.dev.java.net/guice/ (Strangely harder than JAX-RS)

Weitere ähnliche Inhalte

Was ist angesagt?

End to end todo list app with NestJs - Angular - Redux & Redux Saga
End to end todo list app with NestJs - Angular - Redux & Redux SagaEnd to end todo list app with NestJs - Angular - Redux & Redux Saga
End to end todo list app with NestJs - Angular - Redux & Redux SagaBabacar NIANG
 
Advanced VCL: how to use restart
Advanced VCL: how to use restartAdvanced VCL: how to use restart
Advanced VCL: how to use restartFastly
 
Is writing performant code too expensive?
Is writing performant code too expensive? Is writing performant code too expensive?
Is writing performant code too expensive? Tomasz Kowalczewski
 
Design & Performance - Steve Souders at Fastly Altitude 2015
Design & Performance - Steve Souders at Fastly Altitude 2015Design & Performance - Steve Souders at Fastly Altitude 2015
Design & Performance - Steve Souders at Fastly Altitude 2015Fastly
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAnkit Agarwal
 
Solving anything in VCL
Solving anything in VCLSolving anything in VCL
Solving anything in VCLFastly
 
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech TalkHacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech TalkRed Hat Developers
 
Data Loading Made Easy with Mike Nakhimovich DroidCon Italy 2017
Data Loading Made Easy with Mike Nakhimovich DroidCon Italy 2017Data Loading Made Easy with Mike Nakhimovich DroidCon Italy 2017
Data Loading Made Easy with Mike Nakhimovich DroidCon Italy 2017Mike Nakhimovich
 
Sane Sharding with Akka Cluster
Sane Sharding with Akka ClusterSane Sharding with Akka Cluster
Sane Sharding with Akka Clustermiciek
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJiayun Zhou
 
OSGi Puzzlers - Neil Bartlett & Peter Kriens
OSGi Puzzlers - Neil Bartlett & Peter KriensOSGi Puzzlers - Neil Bartlett & Peter Kriens
OSGi Puzzlers - Neil Bartlett & Peter Kriensmfrancis
 
Martin Anderson - threads v actors
Martin Anderson - threads v actorsMartin Anderson - threads v actors
Martin Anderson - threads v actorsbloodredsun
 
Tech Talks_25.04.15_Session 3_Tibor Sulyan_Distributed coordination with zook...
Tech Talks_25.04.15_Session 3_Tibor Sulyan_Distributed coordination with zook...Tech Talks_25.04.15_Session 3_Tibor Sulyan_Distributed coordination with zook...
Tech Talks_25.04.15_Session 3_Tibor Sulyan_Distributed coordination with zook...EPAM_Systems_Bulgaria
 
Provisioning with OSGi Subsystems and Repository using Apache Aries and Felix
Provisioning with OSGi Subsystems and Repository using Apache Aries and FelixProvisioning with OSGi Subsystems and Repository using Apache Aries and Felix
Provisioning with OSGi Subsystems and Repository using Apache Aries and FelixDavid Bosschaert
 
Altitude NY 2018: Programming the edge workshop
Altitude NY 2018: Programming the edge workshopAltitude NY 2018: Programming the edge workshop
Altitude NY 2018: Programming the edge workshopFastly
 
Swift on Raspberry Pi
Swift on Raspberry PiSwift on Raspberry Pi
Swift on Raspberry PiSally Shepard
 

Was ist angesagt? (20)

End to end todo list app with NestJs - Angular - Redux & Redux Saga
End to end todo list app with NestJs - Angular - Redux & Redux SagaEnd to end todo list app with NestJs - Angular - Redux & Redux Saga
End to end todo list app with NestJs - Angular - Redux & Redux Saga
 
Advanced VCL: how to use restart
Advanced VCL: how to use restartAdvanced VCL: how to use restart
Advanced VCL: how to use restart
 
Is writing performant code too expensive?
Is writing performant code too expensive? Is writing performant code too expensive?
Is writing performant code too expensive?
 
Design & Performance - Steve Souders at Fastly Altitude 2015
Design & Performance - Steve Souders at Fastly Altitude 2015Design & Performance - Steve Souders at Fastly Altitude 2015
Design & Performance - Steve Souders at Fastly Altitude 2015
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
Enterprise Java Puzzlers
Enterprise Java PuzzlersEnterprise Java Puzzlers
Enterprise Java Puzzlers
 
Solving anything in VCL
Solving anything in VCLSolving anything in VCL
Solving anything in VCL
 
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech TalkHacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
 
Data Loading Made Easy with Mike Nakhimovich DroidCon Italy 2017
Data Loading Made Easy with Mike Nakhimovich DroidCon Italy 2017Data Loading Made Easy with Mike Nakhimovich DroidCon Italy 2017
Data Loading Made Easy with Mike Nakhimovich DroidCon Italy 2017
 
Sane Sharding with Akka Cluster
Sane Sharding with Akka ClusterSane Sharding with Akka Cluster
Sane Sharding with Akka Cluster
 
Celery
CeleryCelery
Celery
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
 
OSGi Puzzlers - Neil Bartlett & Peter Kriens
OSGi Puzzlers - Neil Bartlett & Peter KriensOSGi Puzzlers - Neil Bartlett & Peter Kriens
OSGi Puzzlers - Neil Bartlett & Peter Kriens
 
Martin Anderson - threads v actors
Martin Anderson - threads v actorsMartin Anderson - threads v actors
Martin Anderson - threads v actors
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
Tech Talks_25.04.15_Session 3_Tibor Sulyan_Distributed coordination with zook...
Tech Talks_25.04.15_Session 3_Tibor Sulyan_Distributed coordination with zook...Tech Talks_25.04.15_Session 3_Tibor Sulyan_Distributed coordination with zook...
Tech Talks_25.04.15_Session 3_Tibor Sulyan_Distributed coordination with zook...
 
Hands on: Hystrix
Hands on: HystrixHands on: Hystrix
Hands on: Hystrix
 
Provisioning with OSGi Subsystems and Repository using Apache Aries and Felix
Provisioning with OSGi Subsystems and Repository using Apache Aries and FelixProvisioning with OSGi Subsystems and Repository using Apache Aries and Felix
Provisioning with OSGi Subsystems and Repository using Apache Aries and Felix
 
Altitude NY 2018: Programming the edge workshop
Altitude NY 2018: Programming the edge workshopAltitude NY 2018: Programming the edge workshop
Altitude NY 2018: Programming the edge workshop
 
Swift on Raspberry Pi
Swift on Raspberry PiSwift on Raspberry Pi
Swift on Raspberry Pi
 

Andere mochten auch

Bombay Sapphire's Most Imaginative Bartender
Bombay Sapphire's Most Imaginative BartenderBombay Sapphire's Most Imaginative Bartender
Bombay Sapphire's Most Imaginative BartenderMajor Brands
 
Neon response to bombay sapphire pitch 18.07.12 final
Neon response to bombay sapphire pitch 18.07.12 finalNeon response to bombay sapphire pitch 18.07.12 final
Neon response to bombay sapphire pitch 18.07.12 finalNick Cunningham
 
Nelsons Gin Brochure (low res) [395909]
Nelsons Gin Brochure (low res) [395909]Nelsons Gin Brochure (low res) [395909]
Nelsons Gin Brochure (low res) [395909]Greg Kimber
 

Andere mochten auch (6)

Bombay Sapphire's Most Imaginative Bartender
Bombay Sapphire's Most Imaginative BartenderBombay Sapphire's Most Imaginative Bartender
Bombay Sapphire's Most Imaginative Bartender
 
Neon response to bombay sapphire pitch 18.07.12 final
Neon response to bombay sapphire pitch 18.07.12 finalNeon response to bombay sapphire pitch 18.07.12 final
Neon response to bombay sapphire pitch 18.07.12 final
 
Nelsons Gin Brochure (low res) [395909]
Nelsons Gin Brochure (low res) [395909]Nelsons Gin Brochure (low res) [395909]
Nelsons Gin Brochure (low res) [395909]
 
RUM AND GIN
RUM AND GINRUM AND GIN
RUM AND GIN
 
Gin
GinGin
Gin
 
Gin
GinGin
Gin
 

Ähnlich wie Guice gin

Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejugrobbiev
 
Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice PresentationDmitry Buzdin
 
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-finalDroidcon Berlin
 
Das kannste schon so machen
Das kannste schon so machenDas kannste schon so machen
Das kannste schon so machenAndré Goliath
 
Cassandra Day NY 2014: Getting Started with the DataStax C# Driver
Cassandra Day NY 2014: Getting Started with the DataStax C# DriverCassandra Day NY 2014: Getting Started with the DataStax C# Driver
Cassandra Day NY 2014: Getting Started with the DataStax C# DriverDataStax Academy
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
OSGi Enterprise R6 specs are out! - David Bosschaert & Carsten Ziegeler
OSGi Enterprise R6 specs are out! - David Bosschaert & Carsten ZiegelerOSGi Enterprise R6 specs are out! - David Bosschaert & Carsten Ziegeler
OSGi Enterprise R6 specs are out! - David Bosschaert & Carsten Ziegelermfrancis
 
Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web ToolkitsYiguang Hu
 
SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8Ben Abdallah Helmi
 
Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Savio Sebastian
 
Getting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net DriverGetting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net DriverDataStax Academy
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testabilitydrewz lin
 
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011telestax
 
06 response-headers
06 response-headers06 response-headers
06 response-headerssnopteck
 

Ähnlich wie Guice gin (20)

Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejug
 
Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice Presentation
 
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
 
Devoxx 2012 (v2)
Devoxx 2012 (v2)Devoxx 2012 (v2)
Devoxx 2012 (v2)
 
GWT MVP Case Study
GWT MVP Case StudyGWT MVP Case Study
GWT MVP Case Study
 
Das kannste schon so machen
Das kannste schon so machenDas kannste schon so machen
Das kannste schon so machen
 
GWT Extreme!
GWT Extreme!GWT Extreme!
GWT Extreme!
 
Cassandra Day NY 2014: Getting Started with the DataStax C# Driver
Cassandra Day NY 2014: Getting Started with the DataStax C# DriverCassandra Day NY 2014: Getting Started with the DataStax C# Driver
Cassandra Day NY 2014: Getting Started with the DataStax C# Driver
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Guice
GuiceGuice
Guice
 
Guice
GuiceGuice
Guice
 
OSGi Enterprise R6 specs are out! - David Bosschaert & Carsten Ziegeler
OSGi Enterprise R6 specs are out! - David Bosschaert & Carsten ZiegelerOSGi Enterprise R6 specs are out! - David Bosschaert & Carsten Ziegeler
OSGi Enterprise R6 specs are out! - David Bosschaert & Carsten Ziegeler
 
guice-servlet
guice-servletguice-servlet
guice-servlet
 
Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web Toolkits
 
SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8
 
Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2
 
Getting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net DriverGetting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net Driver
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
 
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
 
06 response-headers
06 response-headers06 response-headers
06 response-headers
 

Mehr von Robert Cooper

Mehr von Robert Cooper (6)

What's New in Android
What's New in AndroidWhat's New in Android
What's New in Android
 
Android 3
Android 3Android 3
Android 3
 
GWT is Smarter Than You
GWT is Smarter Than YouGWT is Smarter Than You
GWT is Smarter Than You
 
Android Froyo
Android FroyoAndroid Froyo
Android Froyo
 
Extreme Source Compatibility
Extreme Source CompatibilityExtreme Source Compatibility
Extreme Source Compatibility
 
GWT 2 Is Smarter Than You
GWT 2 Is Smarter Than YouGWT 2 Is Smarter Than You
GWT 2 Is Smarter Than You
 

Kürzlich hochgeladen

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
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...Martijn de Jong
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
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 MenDelhi Call girls
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
[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.pdfhans926745
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
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...Neo4j
 
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 Processorsdebabhi2
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
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 organizationRadu Cotescu
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
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 WorkerThousandEyes
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 

Kürzlich hochgeladen (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
[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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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...
 
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
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
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
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 

Guice gin

  • 1. Sapphire Gimlets* Robert Cooper ReachCall.com *no onions
  • 2. Guice Dependency Injection Java Source configuration Convention over configuration Fast
  • 3. Gin Guice for GWT apps 100% Client Side Based on Deferred Binding, so some limitations Fast
  • 4. Guicevs Spring Spring Config Hell Promise of simplicity Ever expanding config files Lots of subprojects Becomes more brittle, in that it becomes harder to extract code for reuse.
  • 5. Guicevs Spring Guice Java Source “configuration” Convention over configuration. Annotation based Opposite of Spring in defaults Prefer constructor injection Prefer new instances (“Prototype”) over Singletons Provider<T> interface encourages mixing scopes Type Safe – you got static typing, use it!
  • 6. Guice 101 Basic Annotations @Inject @ImplementedBy/@ProvidedBy @[Scope] @Named
  • 7. Guice 101 public class MyClass { private final MyService service; @Injectpublic MyClass(finalMyService service){this.service = service;} public String sayHelloToUser(){ return this.service.hello();} } @ImplementedBy(MyServiceImpl.class)public interface MyService { public String hello();}
  • 8. Guice 101 @Singleton public class MyServiceImpl implements MyService { private final Provider<MySessionObject> sessionProvider; public MyServiceImpl(final Provider<MySessionObject> sessionProvider){ this.sessionProvider = sessionProvider; } @Override public String hello() { return "Hello, "+sessionProvider.get().getName() +"!"; } }
  • 9. Guice 101 import com.google.inject.servlet.SessionScoped; @SessionScoped public class MySessionObject { private String name; public String getName(){ return this.name; } public void setName(String name){ this.name = name; } }
  • 10. Guice 101 What have we done? MyClass gets a MyService injected. MyService is implemented by MyServiceImpl as a Singleton MyServiceImpl gets a Provider<MySessionObject> The hello() method fetches the Session scoped MySession object, and says Hello!
  • 11. Guice 101 @ImplementedBy provides defaults for any interface (You don’t need to config these if the default is OK) Injection is type safe on constructors (Unit tests have obvious requirements) Scope annotations (@SessionScoped, @Singleton) provide defaults. Provider<T> hides the scope shift from the Singleton service in a single thread method.
  • 12. Guice 101 Making it work on the web…
  • 13. Guice 101 public class GuiceContextListener extends GuiceServletContextListener { @Override protected Injector getInjector() { return Guice.createInjector( new Module() { public void configure(Binder binder) { // Oh Wait, we don’t need anything here! } } }, new ServletModule() { @Override protected void configureServlets() { this.serve(“/myPath/*”).with(MyServlet.class); } } } }
  • 14. Guice 101 Warning! Overly complicated coming up!
  • 15. Guice 101 @Singleton public class MyServlet extends HttpServlet{ private final Provider<MySessionObject> sessionProvider; private final MyClassmyClass; @Inject public MyServlet(final Provider<MySessionObject> sessionProvider, MyClassmyClass){ this.sessionProvider = sessionProvider; this.myClass = myClass; } @Override public void doGet(HttpServletRequestreq, HttpServletResponse res) throws IOException { this.sessionProvider.get().setName(req.getParameter("name")); res.getWriter().println(myClass.hello()); } }
  • 16. Guice 101 So this is interesting. What happened there? The SessionScoped object was created, and set on the session. MyClass was created one off for injection into the servlet. Since it wasn’t a Provider<MyClass> it was implicitly @Singleton with the servlet But since the MyClass implementation used a provider, it ended up performing a singleton-session scoped op.
  • 17. Guice 101 What else? Servlets, Filters, etc must always be @Singleton of course, this just makes sense. They can *still* get anything injected into them. You need to add your boostrapGuiceContextListener to your web.xml For Servlet < 3.0 you need to add a com.google.inject.servlet.GuiceFilter to /*
  • 18. Guice 201 Why does this rock? (Hint GWT stuff…) Can you say RemoteServiceServlet? No more calls to getThreadLocalX() for servlet context stuff. Just use Provider<T>
  • 19. Guice 201: Warp The Warp-* projects provide a lot of utility ops for Guice: @Transactional scope Transaction per Request Some stuff not dissimilar to Spring WebFlow or Stripes.
  • 20. Guice 201: More Config @Named lets you provide named values in your configuration. (You can also create custom annotations) You can also use @Provides for factory methods in your modules for simple providers @Provides public Connection getConnection(@Named(“jdbc-url”) String jdbcUrl) { DriverManager.forName(whatever); DriverManager.getConnection(jdbcUrl); }
  • 21. Guice 201: More Config binder.bind(String.class).annotatedWith(Names.named(“jdbc-url”)).toInstance(“jdbc:mysql://localhost/mydb”); Note: @Provides methods could do JNDI lookups, or get other stuff. (This is a stupid example!)
  • 22. Of Junipers and Bathtubs Gin is Google Guice for GWT client side apps. Based on DeferrredBinding. Certain features lost: Binding .toInstance() on any module Anonymous Provider<T> can’t be done (@Provides is *kinda* OK) Scoping needs to be by hard class reference.
  • 23. Of Junipers and Bathtubs That is.. in(Singleton.class) not .asEagerSingleton() or with @Singleton Gin seems both stupid and too smart. Binding a RemoteServiceAsync class works out of the box… Unless you want to do @Provides Gin created classes are new Class() not GWT.create(Class.class); -- except for RemoteServiceAsync, which is a special scope.
  • 24. Gin 101 @GinModules(MyGinModule.class) public interface Injector extends Ginjector { public static final Injector INSTANCE = GWT.create(Injector.class); public MyStartupClassstartupClass(); } public classMyGinModuleextends AbstractGinModule { @Override protected void configure() { this.bind(Resources.class) .toProvider(ResourcesProvider.class) .in(Singleton.class) } } public static class ResourcesProvider implements Provider<Resources> { @Override public Resources get() { return GWT.create(Resources.class); } }
  • 25. Gin 101 Does this step on the toes of DeBi? OK, maybe a little bit. Sure you could do a singleton Resources.INSTANCE but injection makes Unit testing without dropping into GWTTestCase more frequent. (Read: much, much faster) This reserves DeBi for what it is best for: local environment specific code.
  • 26. Gin 201 What can’t you do with Gin? Remember your Injector.INSTANCE is compile-time: No “toInstance()” bindings… ever. No “toProvider(AnonymousProvider(){})” providers need to be public scoped static classes at the least. Gin treats RemoteServiceAsync specially. You can do a provider, but if you try @Provides methods in your GinModule classes, you will get a duplicate declaration error.
  • 27. Gin 201 All this aside, stacked with DeBi, Gin can rock rough and stuff with its Afro Puffs. Replace your Startup call with a Sync method. Replace your Async classes with thing that talk to local storage. Automagically retry onFailure() methods on network errors while your uses if offline.
  • 28. Way way more Warp-* is some great stuff: http://code.google.com/p/warp-persist/ http://code.google.com/p/google-sitebricks/ Guice with JAX-WShttps://jax-ws-commons.dev.java.net/guice/ (Strangely harder than JAX-RS)