SlideShare a Scribd company logo
1 of 13
Download to read offline
Google Guice

Depencency injection framework
Basic facts

  Pure Java
     no external configuration files (compared to Spring)
     bindings configuration in modules (Java classes)

  Uses annotations and generics
     type safe
     easy refactoring in your IDE
     requires Java 5

  Open source under Apache License 2.0

  Integration with Servlets, Struts2 ans Spring possible
Simple example

Simple application with database and JUnit tests
Simple example

 Class UserController
    subject of JUnit tests
    requires a database

 Interface DAO - abstraction of all database operations
     Class JdbcDAO - quot;realquot; databse
     Class TestDAO - mockup implementation for JUnit tests

  How does UserController get an instance of DAO?
UserController

class UserController {
    private DAO dao;


    public UserController() {

    }

    public void someMethod {
        List<User> users = dao.getUsers();
        ....
    }
}
UserController - with Guice

class UserController {
    private DAO dao;

    @Inject
    public UserController(DAO dao) {
        this.dao = dao;
    }

    public void someMethod {
        List<User> users = dao.getUsers();
        ....
    }
}
UserController - with Guice (alternative)

class UserController {
    @Inject
    private DAO dao;

    public UserController() {

    }

    public void someMethod {
        List<User> users = dao.getUsers();
        ....
    }
}
Configuration - JUnit Tests

public class TestModule extends AbstractModule
{

    public void configure() {
        bind(DAO.class).to(TestDAO.class);
    }

}
Configuration - Application

public class AppModule extends AbstractModule
{

    public void configure() {
        bind(DAO.class).to(JdbcDAO.class);

    }

}
Bind to ...

  bind(DAO.class).to(TestDAO.class);

  bind(DAO.class).to(TestDAO.class)
    .in(Scopes.SINGLETON);

  bind(DAO.class).toInstance(new TestDAO());

  bind(DAO.class).toProvider(DAOFactory.
  class);

  Default implementation: @ImplementedBy
MyApplication

public static void main(String[] args) {
    ...
    Injector injector =
        Guice.createInjector(new AppModule());

    UserController userController =
        injector.
        getInstance(UserController.class);
}
JUnit Test

@Before
public void setup() {
    Injector injector =
        Guice.createInjector(new TestModule());

    UserController userController =
        injector.
        getInstance(UserController.class);
}
Much more...

   Annotated with:
@Inject
public SomeConstructor(@Blue DAO dao);
...
bind(DAO.class).
    annotatedWith(Blue.class).
    to(....);

  Annotations with attributes

  ServletScopes.SESSION bzw. REQUEST

  SringIntegration

More Related Content

What's hot

Introduction to Drools
Introduction to DroolsIntroduction to Drools
Introduction to Drools
giurca
 
Android application model
Android application modelAndroid application model
Android application model
magicshui
 

What's hot (20)

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
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoC
 
Annotation Processing in Android
Annotation Processing in AndroidAnnotation Processing in Android
Annotation Processing in Android
 
Drools rule Concepts
Drools rule ConceptsDrools rule Concepts
Drools rule Concepts
 
TY.BSc.IT Java QB U2
TY.BSc.IT Java QB U2TY.BSc.IT Java QB U2
TY.BSc.IT Java QB U2
 
Introduction to Drools
Introduction to DroolsIntroduction to Drools
Introduction to Drools
 
Rule Engine & Drools
Rule Engine & DroolsRule Engine & Drools
Rule Engine & Drools
 
Rules Engine - java(Drools) & ruby(ruleby)
Rules Engine - java(Drools) & ruby(ruleby)Rules Engine - java(Drools) & ruby(ruleby)
Rules Engine - java(Drools) & ruby(ruleby)
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
 
Reproducible component tests using docker
Reproducible component tests using dockerReproducible component tests using docker
Reproducible component tests using docker
 
What's new in Android O
What's new in Android OWhat's new in Android O
What's new in Android O
 
#11.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원학원,재직자/실업자교육학원,스프링교육,마이바...
#11.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원학원,재직자/실업자교육학원,스프링교육,마이바...#11.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원학원,재직자/실업자교육학원,스프링교육,마이바...
#11.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원학원,재직자/실업자교육학원,스프링교육,마이바...
 
React Native: JS MVC Meetup #15
React Native: JS MVC Meetup #15React Native: JS MVC Meetup #15
React Native: JS MVC Meetup #15
 
Android application model
Android application modelAndroid application model
Android application model
 
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
 
Reverse Engineering 안드로이드 학습
Reverse Engineering 안드로이드 학습Reverse Engineering 안드로이드 학습
Reverse Engineering 안드로이드 학습
 
Architecture Components
Architecture Components Architecture Components
Architecture Components
 
Java 9
Java 9Java 9
Java 9
 
JBoss Drools - Pure Java Rule Engine
JBoss Drools - Pure Java Rule EngineJBoss Drools - Pure Java Rule Engine
JBoss Drools - Pure Java Rule Engine
 

Similar to JSUG - Google Guice by Jan Zarnikov

Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
C.T.Co
 
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
 
Powerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatisPowerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatis
simonetripodi
 

Similar to JSUG - Google Guice by Jan Zarnikov (20)

Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
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"
 
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
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
MVM - It's all in the (Implementation) Details
MVM - It's all in the (Implementation) DetailsMVM - It's all in the (Implementation) Details
MVM - It's all in the (Implementation) Details
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
 
guice-servlet
guice-servletguice-servlet
guice-servlet
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
Android Architecture Components - Guy Bar on, Vonage
Android Architecture Components - Guy Bar on, VonageAndroid Architecture Components - Guy Bar on, Vonage
Android Architecture Components - Guy Bar on, Vonage
 
Architecture components - IT Talk
Architecture components - IT TalkArchitecture components - IT Talk
Architecture components - IT Talk
 
Devoxx 2012 (v2)
Devoxx 2012 (v2)Devoxx 2012 (v2)
Devoxx 2012 (v2)
 
Powerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatisPowerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatis
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSpring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing Support
 
Resthub framework presentation
Resthub framework presentationResthub framework presentation
Resthub framework presentation
 
Spring 3 to 4
Spring 3 to 4Spring 3 to 4
Spring 3 to 4
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15
 
Building Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsBuilding Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture Components
 
CDI @javaonehyderabad
CDI @javaonehyderabadCDI @javaonehyderabad
CDI @javaonehyderabad
 

More from Christoph Pickl

More from Christoph Pickl (20)

JSUG - AS3 vs Java by Christoph Pickl
JSUG - AS3 vs Java by Christoph PicklJSUG - AS3 vs Java by Christoph Pickl
JSUG - AS3 vs Java by Christoph Pickl
 
JSUG - Layouting TeX documents with the Memoir class
JSUG - Layouting TeX documents with the Memoir classJSUG - Layouting TeX documents with the Memoir class
JSUG - Layouting TeX documents with the Memoir class
 
JSUG - Cocoon3 Student Project Idea by Reinhard Poetz and Steven Dolg
JSUG - Cocoon3 Student Project Idea by Reinhard Poetz and Steven DolgJSUG - Cocoon3 Student Project Idea by Reinhard Poetz and Steven Dolg
JSUG - Cocoon3 Student Project Idea by Reinhard Poetz and Steven Dolg
 
JSUG - ActionScript 3 vs Java by Christoph Pickl
JSUG - ActionScript 3 vs Java by Christoph PicklJSUG - ActionScript 3 vs Java by Christoph Pickl
JSUG - ActionScript 3 vs Java by Christoph Pickl
 
JSUG - TeX, LaTeX und der Rest by Norbert Preining
JSUG - TeX, LaTeX und der Rest by Norbert PreiningJSUG - TeX, LaTeX und der Rest by Norbert Preining
JSUG - TeX, LaTeX und der Rest by Norbert Preining
 
JSUG - TeX Day by Christoph Pickl
JSUG - TeX Day by Christoph PicklJSUG - TeX Day by Christoph Pickl
JSUG - TeX Day by Christoph Pickl
 
JSUG - The Sound of Shopping by Christoph Pickl
JSUG - The Sound of Shopping by Christoph PicklJSUG - The Sound of Shopping by Christoph Pickl
JSUG - The Sound of Shopping by Christoph Pickl
 
JSUG - Tim aka EPROG2 by Martin Schuerrer
JSUG - Tim aka EPROG2 by Martin SchuerrerJSUG - Tim aka EPROG2 by Martin Schuerrer
JSUG - Tim aka EPROG2 by Martin Schuerrer
 
JSUG - Java Service Enabler by Andreas Hubmer
JSUG - Java Service Enabler by Andreas HubmerJSUG - Java Service Enabler by Andreas Hubmer
JSUG - Java Service Enabler by Andreas Hubmer
 
JSUG - Hoppla by Florian Motlik and Petar Petrov
JSUG - Hoppla by Florian Motlik and Petar PetrovJSUG - Hoppla by Florian Motlik and Petar Petrov
JSUG - Hoppla by Florian Motlik and Petar Petrov
 
JSUG - Google Web Toolkit by Hans Sowa
JSUG - Google Web Toolkit by Hans SowaJSUG - Google Web Toolkit by Hans Sowa
JSUG - Google Web Toolkit by Hans Sowa
 
JSUG - TU Wien Cocoon Project by Andreas Pieber
JSUG - TU Wien Cocoon Project by Andreas PieberJSUG - TU Wien Cocoon Project by Andreas Pieber
JSUG - TU Wien Cocoon Project by Andreas Pieber
 
JSUG - TU Wien Castor Project by Lukas Lang
JSUG - TU Wien Castor Project by Lukas LangJSUG - TU Wien Castor Project by Lukas Lang
JSUG - TU Wien Castor Project by Lukas Lang
 
JSUG - LaTeX Introduction by Christoph Pickl
JSUG - LaTeX Introduction by Christoph PicklJSUG - LaTeX Introduction by Christoph Pickl
JSUG - LaTeX Introduction by Christoph Pickl
 
JSUG - OSGi by Michael Greifeneder
JSUG - OSGi by Michael GreifenederJSUG - OSGi by Michael Greifeneder
JSUG - OSGi by Michael Greifeneder
 
JSUG - Filthy Flex by Christoph Pickl
JSUG - Filthy Flex by Christoph PicklJSUG - Filthy Flex by Christoph Pickl
JSUG - Filthy Flex by Christoph Pickl
 
JSUG - Seam by Florian Motlik
JSUG - Seam by Florian MotlikJSUG - Seam by Florian Motlik
JSUG - Seam by Florian Motlik
 
JSUG - Java FX by Christoph Pickl
JSUG - Java FX by Christoph PicklJSUG - Java FX by Christoph Pickl
JSUG - Java FX by Christoph Pickl
 
JSUG - Tech Tips1 by Christoph Pickl
JSUG - Tech Tips1 by Christoph PicklJSUG - Tech Tips1 by Christoph Pickl
JSUG - Tech Tips1 by Christoph Pickl
 
JSUG - Inversion Of Control by Florian Motlik
JSUG - Inversion Of Control by Florian MotlikJSUG - Inversion Of Control by Florian Motlik
JSUG - Inversion Of Control by Florian Motlik
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
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
Earley Information Science
 
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
Enterprise Knowledge
 

Recently uploaded (20)

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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.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...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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 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
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
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
 
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
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

JSUG - Google Guice by Jan Zarnikov

  • 2. Basic facts Pure Java no external configuration files (compared to Spring) bindings configuration in modules (Java classes) Uses annotations and generics type safe easy refactoring in your IDE requires Java 5 Open source under Apache License 2.0 Integration with Servlets, Struts2 ans Spring possible
  • 3. Simple example Simple application with database and JUnit tests
  • 4. Simple example Class UserController subject of JUnit tests requires a database Interface DAO - abstraction of all database operations Class JdbcDAO - quot;realquot; databse Class TestDAO - mockup implementation for JUnit tests How does UserController get an instance of DAO?
  • 5. UserController class UserController { private DAO dao; public UserController() { } public void someMethod { List<User> users = dao.getUsers(); .... } }
  • 6. UserController - with Guice class UserController { private DAO dao; @Inject public UserController(DAO dao) { this.dao = dao; } public void someMethod { List<User> users = dao.getUsers(); .... } }
  • 7. UserController - with Guice (alternative) class UserController { @Inject private DAO dao; public UserController() { } public void someMethod { List<User> users = dao.getUsers(); .... } }
  • 8. Configuration - JUnit Tests public class TestModule extends AbstractModule { public void configure() { bind(DAO.class).to(TestDAO.class); } }
  • 9. Configuration - Application public class AppModule extends AbstractModule { public void configure() { bind(DAO.class).to(JdbcDAO.class); } }
  • 10. Bind to ... bind(DAO.class).to(TestDAO.class); bind(DAO.class).to(TestDAO.class) .in(Scopes.SINGLETON); bind(DAO.class).toInstance(new TestDAO()); bind(DAO.class).toProvider(DAOFactory. class); Default implementation: @ImplementedBy
  • 11. MyApplication public static void main(String[] args) { ... Injector injector = Guice.createInjector(new AppModule()); UserController userController = injector. getInstance(UserController.class); }
  • 12. JUnit Test @Before public void setup() { Injector injector = Guice.createInjector(new TestModule()); UserController userController = injector. getInstance(UserController.class); }
  • 13. Much more... Annotated with: @Inject public SomeConstructor(@Blue DAO dao); ... bind(DAO.class). annotatedWith(Blue.class). to(....); Annotations with attributes ServletScopes.SESSION bzw. REQUEST SringIntegration