如何理解依赖注入?

来源:学生作业帮助网 编辑:作业帮 时间:2024/04/29 07:28:33
如何理解依赖注入?

如何理解依赖注入?
如何理解依赖注入?

如何理解依赖注入?
人有时候需要用手机打电话,需要用到手机的dialUp方法.
传统的写法是这样:Java code
public class Person{
public boolean makeCall(long number){
Mobile mobile=new Mobile();
return mobile.dialUp(number);}}
也就是说,类Person的makeCall方法对Mobile类具有依赖,必须手动生成一个新的实例new Mobile()才可以进行之后的工作.
依赖注入的思想是这样,当一个类(Person)对另一个类(Mobile)有依赖时,不再该类(Person)内部对依赖的类(Moblile)进行实例化,而是之前配置一个beans.xml,告诉容器所依赖的类(Mobile),在实例化该类(Person)时,容器自动注入一个所依赖的类(Mobile)的实例.
接口:Java code
public Interface MobileInterface{
public boolean dialUp(long number);}Person类:Java code
public class Person{
private MobileInterface mobileInterface;
public boolean makeCall(long number){
return this.mobileInterface.dialUp(number);}public void setMobileInterface(MobileInterface mobileInterface){
this.mobileInterface=mobileInterface;}}在xml文件中配置依赖关系Java code<bean id="person" class="Person"
<property name="mobileInterface"
<ref local="mobileInterface"/