春季构造函数注入和二传手注入之间的区别
依赖注入是一种将依赖对象传递给其他对象的实践。Spring有两种类型的依赖注入:
基于构造函数的Injection-When容器调用类的构造函数。它应用于强制性依赖项。
假设X类紧密依赖于Y类,那么我们应该使用基于构造函数的注入。
基于Setter的注入-可以通过在bean上调用setter方法来使用它。它应该用于可选的依赖项。
两种类型的注入都有其优缺点。以下是一些差异的列表-
构造函数注入示例
public class ConstructorInjectionExample {
public ConstructorInjectionExample(BaseExmp baseExmp) {
//...-
}
}
<beans>
<bean id = "ConstructorInjectionExample" class = "x.y.ConstructorInjectionExample">
<constructor-arg ref = "baseExmp"/>
</bean>
<bean id = "baseExmp" class = "x.y.BaseExmp"/>
</beans>二传手注入的例子
public class SetterInjectionExample {
public void setBaseExmp(BaseExmp baseExmp) {
this.baseExmp = baseExmp;
}
}
<beans>
<bean id = "setterInjectionExample" class = "x.y.SetterInjectionExample">
<property name = "baseExmp" ref = "baseExmp"/>
</bean>
</beans>