spring依赖注入
来源:互联网 发布:北京海量数据 干嘛的? 编辑:程序博客网 时间:2024/06/16 15:03
先看一段代码
假设你编写了两个类,一个是人(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类完成,并在使用时由容器自动注入,这样大大降低了不同类间相互依赖的关系。
还有一部反射机制的精彩文章:http://blog.csdn.net/woshixuye/article/details/7700455
还有依赖注入和控制反转的定义:http://blog.csdn.net/jianyuerensheng/article/details/50837171
0 0
- Spring依赖注入:注解注入
- spring 的依赖注入
- Spring依赖注入实践经验
- Spring的依赖注入
- Spring依赖注入
- spring(依赖注入-DI)
- spring依赖注入
- spring依赖注入
- 白话spring依赖注入
- Spring依赖注入方式
- Spring的依赖注入
- Spring依赖注入
- Spring依赖注入方式
- Spring 依赖注入
- spring依赖注入方式
- spring的依赖注入
- Spring依赖注入方式
- Spring依赖注入方式:
- Android混淆应注意的编码习惯
- Android书单
- 0314-form表单标签的使用
- 看懂RS232,RS485,TTL
- mysql的触发器
- spring依赖注入
- MySQl 获得表的下一个自增值
- Java创建线程的两种方式
- 【软件可靠性】失效数据
- MySQL常用函数学习
- Web框架系列:Session的实现原理
- mina源码分析
- bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: html5lib
- 针对 IDEA 开发工具崩溃 导致的项目工程异常的解决方案