首先,把Spring需要的五个包导入项目:

commons-logging-1.2.jar

spring-beans-4.3.4.RELEASE.jar

spring-context-4.3.4.RELEASE.jar

spring-core-4.3.4.RELEASE.jar

spring-expression-4.3.4.RELEASE.jar

然后就可以敲代码了:

什么是控制反转

需要获取一个接口的实现类的时候,向spring框架请求它的一个实现类,而不是直接new一个。

 @Test
public void Demo() {
String xml="applicationContext.xml";
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xml);
SpringService springService=(SpringService) applicationContext.getBean("springService");
springService.UserDesign();
// applicationContext.close();
}

Spring的方法

     @Test
public void Demo2(){
SpringService springService=new SpringServiceImpl();
springService.UserDesign();
}

没有Spring的时候

在没有Spring的时候其实现代码中出现了字段“SpringServiceImpl”,而在Spring的实现时却没有出现。

这就意味着,当我们需要用接口SpringService的另一个实现类(假设是SpringServiceImpl2)来取代SpringServiceImpl时,在第二种情况下必须修改源代码,将字段“SpringServiceImpl”替换为字段“SpringServiceImpl2”。

而在 第一种情况下则不需要,因为实现类的名字并没有在源代码中出现。

Spring是怎么知道我们需要的是SpringService的实现类的呢?

它是通过这个知道的:

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- bean definitions here -->
<bean id="springService" class="com.lille.service.impl.SpringServiceImpl"></bean>
</beans>

XML配置文件

关键就在于配置文件的第八行,这个bean元素。

它的id属性值为“springService”,class属性值为“com.lille.service.impl.SpringServiceImpl”

当这个xml文件通过以下两行代码被加载之后,

 String xml="applicationContext.xml";
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xml);

加载代码

我们的Spring框架就知道了:

当ApplicationContext这个接口的getBean()方法接收到的参数为“springService”时,将“com.lille.service.impl.SpringServiceImpl”这个类实例化然后return。

假设我们希望用SpringService的另一个实现类来取代它,那么我们只需要修改配置文件就可以了,甚至不需要重新编译源代码。

这就是控制反转

最新文章

  1. IOS开发-图片上传
  2. jqGrid 最常用的属性和事件,供平时参考(转)
  3. web storage: sessionStorage 和 localStorage
  4. php和AJAX用户注册演示程序
  5. BZOJ 1218: [HNOI2003]激光炸弹 前缀DP
  6. 【转】hive简介安装 配置常见问题和例子
  7. POJ 2195 Going Home(最小费用最大流)
  8. linux下/proc/sysrq-trigger文件的功能
  9. Android利用tcpdump和wireshark抓取网络数据包
  10. unix IO笔记
  11. [个人翻译]GitHub指导文件(GitHub Guides[Hello World])
  12. 盒模型的垂直居中css
  13. java反射使用和源码解析
  14. LeetCode——17. Letter Combinations of a Phone Number
  15. OO第一单元单元总结
  16. 关于json_encode转数组为json对象时里有数组格式数据的问题
  17. Java 实现倒计时(由秒计算天、小时、分钟、秒)
  18. JavaScript+CSS+DIV实现表格变色示例
  19. mysql索引使用策略及优化
  20. General error 2006 MySQL server has gone away

热门文章

  1. web网页 页面布局的几种方式(转)
  2. Ros学习调试——rqt_console
  3. DesertWind TopCoder - 1570
  4. CF 959E Mahmoud and Ehab and the xor-MST
  5. PersonDto中@ResourceAccess(readOnly = true)以及swagger的理解-----似懂非懂,日后消化
  6. SDUT 3373 数据结构实验之查找一:二叉排序树
  7. HDU 3001 Travelling (状压DP + BFS)
  8. linux core文件机制
  9. [转]10分钟梳理MySQL知识点:揭秘亿级高并发数据库调优与最佳实践法则
  10. Sessions in BSU