美文网首页
Spring 构造方法注入or属性注入

Spring 构造方法注入or属性注入

作者: chrisyoung_3577 | 来源:发表于2020-04-06 19:35 被阅读0次

属性注入( Setter-based Dependency Injection)

基于setter的DI是在调用无参数构造函数或无参数静态工厂方法来实例化bean之后,通过容器调用bean上的setter方法来完成的。

构造方法注入( Constructor-based Dependency Injection )

基于构造函数的DI是通过容器调用带有许多参数的构造函数来完成的,每个参数代表一个依赖项

属性注入or构造方法注入?

1、对于强制依赖的使用构造方法注入

2、对于可选的使用属性注入

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 be a required dependency; however, constructor injection with programmatic validation of arguments is preferable.

相关文章

网友评论

      本文标题:Spring 构造方法注入or属性注入

      本文链接:https://www.haomeiwen.com/subject/bdzbphtx.html