博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring依赖注入的理解
阅读量:6885 次
发布时间:2019-06-27

本文共 1163 字,大约阅读时间需要 3 分钟。

hot3.png

先看一段代码

假设你编写了两个类,一个是人(Person),一个是手机(Mobile)。
人有时候需要用手机打电话,需要用到手机的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"/>
    </property>   
</bean>
<bean id="mobileInterface" class="Mobile"/>
这样,Person类在实现拨打电话的时候,并不知道Mobile类的存在,它只知道调用一个接口MobileInterface,而MobileInterface的具体实现是通过Mobile类完成,并在使用时由容器自动注入,这样大大降低了不同类间相互依赖的关系。

转载于:https://my.oschina.net/u/1423612/blog/288672

你可能感兴趣的文章
Android View 事件分发源码分析
查看>>
vue 2.0 - props
查看>>
RustCon Asia 实录 | Rust 在国内某视频网站的应用
查看>>
Vue遇上Analytics
查看>>
mysql
查看>>
修改max_allowed_packet(允许执行的sql最大长度)
查看>>
node js 处理时间分析
查看>>
判断数据库、表和字段是否存在
查看>>
新手安装postgreSQL后无法连接服务器
查看>>
递归和动态规划
查看>>
java实现简单的控制台管理系统
查看>>
建造模式
查看>>
Java 多线程(四)——线程同步(synchronized、ReentrantLock)
查看>>
遇到Could not load file or assembly ... or one of its dependencies怎么办
查看>>
TCP 上传文件
查看>>
Linux 重定向符:> ,>>, <
查看>>
金融行业注册电子邮箱账号时最需要注意什么?
查看>>
Xhprof安装
查看>>
所谓的linux集群-其实可以so easy
查看>>
关于OOM-killer
查看>>