When and where to use dependency injection with Guice?
I've recently studie开发者_高级运维d 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
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.
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.
精彩评论