Guice vs Dependency Injection By Hand

As you can see, Guice saves you from having to write factory classes. You don't
have to write explicit code wiring clients to their dependencies. If you forget to
provide a dependency, Guice fails at startup.
Guice handles circular dependencies
automatically.
Guice enables you to specify scopes declaratively. For example, you don't have to
write the same code to store an object in the HttpSession over and over.
In the real world, you often don't know an implementation class until runtime.
You need meta factories or service locators for your factories. Guice addresses
these problems with minimal effort.
When injecting dependencies by hand, you can easily slip back into old habits and
introduce direct dependencies, especially if you're new to the concept of
dependency injection. Using Guice turns the tables and makes doing the right
thing easier. Guice helps keep you on track.

现代编译器以及强大的Intellisense已经从很大程度上把程序员从繁琐、重复的工作中解放出来了。但是,这一层面的帮助只是达到了帮助程序员尽快写出正确程序的目的。程序员的coding级别的规范,完全无法约束。像面向抽象的编程,大家很多都很熟悉。但是,实际项目中,新人不见得想得起来用、会用;有经验的不见得时时记得起来用,偶尔会忘是在所难免。结果,依赖关系难以有效管理,从而导致测试工作、维护工作的难以进行。
像Guice做的,我的理解是,把面向抽象、依赖注入这种设计原则提升到了必须通过的“代码设计级check”。通过提供额外的语法比如“@Inject”使得程序员必须遵守依赖注入这一设计原则。如果不遵守,会像编译出错一样报错,这样做,就完全保证了最终完成的代码的更高质量。Guice的理念,体现了现代编程的发展方向--用新的编程框架机制迫使程序员必须理解、并使用新的编程机制,从而在编程实践中自然而然去应用一些非常重要的基本编程准则,比如依赖注入,从而最终进一步提升程序代码质量!
原文地址:https://www.cnblogs.com/taoxu0903/p/1199357.html