Spring学习笔记之Constructor-based or setter-based DI?
2014-12-15 13:23
351 查看
如果是强制依赖,那么使用构造器注入,如果是可选依赖,那么使用set方法注入。Spring鼓励构造器注入,可以确保依赖项不为null, Since you can mix constructor-based and setter-based DI, it is a good rule of thumb to use constructors for mandatory dependencies and setter methods or configuration methods for optional dependencies. Note that use of the @Required annotation on a setter method can be used to make the property a required dependency. The Spring team generally advocates constructor injection as it enables one to implement application components as immutable objects and to ensure that required dependencies are not
null. Furthermore constructor-injected components are always returned to client (calling) code in a fully initialized state. As a side note, a large number of constructor arguments is a bad code smell, implying that the class likely has too many responsibilities and should be refactored to better address proper separation of concerns. Setter injection should primarily only be used for optional dependencies that can be assigned reasonable default values within the class. Otherwise, not-null checks must be performed everywhere the code uses the dependency. One benefit of setter injection is that setter methods make objects of that class amenable to reconfiguration or re-injection later. Management through JMX MBeans is therefore a compelling use case for setter injection. Use the DI style that makes the most sense for a particular class. Sometimes, when dealing with third-party classes for which you do not have the source, the choice is made for you. For example, if a third-party class does not expose any setter methods, then constructor injection may be the only available form of DI.
相关文章推荐
- spring in action 学习笔记(六)通过setter注入bean属性
- ★(转)Spring学习笔记1
- Spring学习笔记:1、概念理解
- Spring in Action 学习笔记—第一章 开始Spring之旅(转贴)
- Spring学习笔记:1-概念理解
- Spring 学习笔记 (二)--AOP
- Modern C++ Design 学习笔记之Policy Based Class Design
- 学习Struts+spring+hibernate的笔记
- Spring学习笔记:1、概念理解
- 学习Struts+spring+Hibernate的笔记.
- Spring学习笔记:第三章 IoC中的国际化
- Spring学习笔记:第三章 IoC中的国际化
- Spring学习笔记:第二章 Spring中IoC的入门实例
- Spring的AOP学习笔记
- Spring学习笔记:1、概念理解
- Spring学习笔记:1、概念理解
- Professional Java Development with the Spring Framework学习笔记(1) - JdbcTemplate 中Query的几种用法
- Spring学习笔记
- Spring学习笔记二
- Spring学习笔记:2-Spring中IoC的入门实例