1点是正确的,创建一个使用新的操作员将 对象导致与依赖紧耦合。请参见下面的 配置: -
<!--This is the material used for construction of structures -->
<bean id="constructionMaterial" class="com.construction.Brick" />
<!--Below are the three constructions structures -->
<bean id="building1" class="com.construction.structures.School">
<property name="material" ref="constructionMaterial" />
</bean>
<bean id="building2" class="com.construction.structures.College">
<property name="material" ref="constructionMaterial" />
</bean>
<bean id="building3" class="com.construction.structures.Hospital">
<property name="material" ref="constructionMaterial" />
</bean>
在上面的例子中假设,如果施工材料改变了我只需要改变constructionMaterial的bean定义。
如果您会使用新的操作符,则必须更改三个班级的学校,学院,医院的代码。还是看起来不错,考虑是否有1000个不同的结构。
依赖注入也使测试非常容易,经过良好测试的代码 是稳定的。
Class A{
public String method1(){
B calcObject=new B();
return "Calculated value is:"+calcObject.calculation();
}
}
如果我需要类A的单元测试方法1(),它不可能做到这一点而不类B,这反过来又冲突单元测试的概念的测试计算()。
如果我改变如以下代码:
Class A{
private B b;
public String method1(){
return "Calculated value is:"+b.calculation();
}
public void setB(B b){
this.b=b;
}
}
在这种情况下,我可以很容易地模拟类B的对象,并执行类的方法1()的单元测试。您可以结帐如何使用模拟对象here执行测试。依赖注入再次成为这里的救星。
第3点不正确,如果您使用的注释类似@Autowired,即使您不使用setter方法或使用参数化构造函数,也没关系。 在这种情况下,依赖项由Reflection注入。
依赖注入的主要目的是为了使测试更加简单 –