JSUG - Google Guice by Jan Zarnikov

1,790 views

Published on

visit http://jsug.fsinf.at

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,790
On SlideShare
0
From Embeds
0
Number of Embeds
11
Actions
Shares
0
Downloads
36
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

JSUG - Google Guice by Jan Zarnikov

  1. 1. Google Guice Depencency injection framework
  2. 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. 3. Simple example Simple application with database and JUnit tests
  4. 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. 5. UserController class UserController { private DAO dao; public UserController() { } public void someMethod { List<User> users = dao.getUsers(); .... } }
  6. 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. 7. UserController - with Guice (alternative) class UserController { @Inject private DAO dao; public UserController() { } public void someMethod { List<User> users = dao.getUsers(); .... } }
  8. 8. Configuration - JUnit Tests public class TestModule extends AbstractModule { public void configure() { bind(DAO.class).to(TestDAO.class); } }
  9. 9. Configuration - Application public class AppModule extends AbstractModule { public void configure() { bind(DAO.class).to(JdbcDAO.class); } }
  10. 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. 11. MyApplication public static void main(String[] args) { ... Injector injector = Guice.createInjector(new AppModule()); UserController userController = injector. getInstance(UserController.class); }
  12. 12. JUnit Test @Before public void setup() { Injector injector = Guice.createInjector(new TestModule()); UserController userController = injector. getInstance(UserController.class); }
  13. 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

×