Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and where to use dependency injection with Guice?

I've recently studied about Guice in a University course, and have seen the Google I/O video about it. In the video, they claim to use it in every Google project, including Wave, etc. I was wondering - is Guice really that ubiquitous? Is it really a must-know-must-use for programmers in Java? Should I always use it over a factory?

Thanks

like image 772
Amir Rachum Avatar asked Jan 22 '23 18:01

Amir Rachum


2 Answers

Guice is a dependency injection framework. When using Java, you should definitely considering dependency injection framework (DI). DI can save you a lot of boiler plate code for (web)security/authentication, transaction management, logging, databaseaccess, and results in cleaner code.

Alternatively you could consider Spring. Guice is, or at least was easier to use as it didn't rely on XML so much, but Spring has caught up since the latest version (using annotations, javaconfig, etc.).

Well, either way, use a DI framework over you're own factory code, transaction boiler plate code (transaction.start . commit, finally .. etc.), singletons (like static getInstance methods), etc.

like image 156
Gerbrand Avatar answered Jan 31 '23 19:01

Gerbrand


is Guice really that ubiquitous? Is it really a must-know-must-use for programmers in Java?

Outside of Google - no, not really. I'm not saying it's not a good product, it just doesn't seem very widely used right now. There are other, more established frameworks out there that provide dependency injection, like Spring or EJB. The main difference is that Guice only does dependency injection.

Should I always use it over a factory?

Of course not. Dependency injection is a useful pattern, but as with all useful tools, there's a right and a wrong time to use it.

like image 23
Mike Baranczak Avatar answered Jan 31 '23 18:01

Mike Baranczak