我是今晚打老虎,点击关注不迷路哦!
什么是控制反转
控制反转(Inversion of Control,缩写为IOC),即,把创建对象的权利交给框架。
也就是指将对象的创建、对象的存储、对象的管理交给了spring容器。
(spring容器是spring中的一个核心模块,用于管理对象,底层可以理解为是一个map集合)
在此之前,当需要对象时,通常是利用new关键字创建一个对象:
/* 获取Service接口的子类实例
* ——这里使用new对象的方式造成了程序之间的耦合性提升 */
private EmpService service = new EmpServiceImpl();
//private EmpService service = (EmpService)BeanFactory.getBean("EmpService");
但由于new对象,会提高类和类之间的依赖关系,即代码之间的耦合性。
而现在我们可以将对象的创建交给框架来做:
/* 获取Service接口的子类实例
* ——这里使用new对象的方式造成了程序之间的耦合性提升 */
//private EmpService service = new EmpServiceImpl();
private EmpService service = (EmpService)BeanFactory.getBean("EmpService");
只需要将类提前配置在配置文件中,就可以将对象的创建交给框架来做。当需要对象时,不需要自己创建,而是通过框架直接获取即可,省去了new对象的过程,自然就降低类和类之间的依赖关系,也就是耦合性。
IOC入门案例
下面将使用spring的IOC解决程序间的耦合
创建Maven工程,引入spring相关依赖包
1、创建Maven—Java工程
2、引入junit、spring的jar包:在maven工程的pom.xml文件的根标签(project)内添加如下配置:
<dependencies>
<!-- 添加junit的jar包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<!-- 添加spring的jar包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
</dependencies>
创建spring核心配置文件—applicationContext.xml
1、在工程的src/main/resources源码目录下,创建applicationContext.xml文件:
2、在applicationContext.xml中添加文件头信息:
<?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">
</beans>
3、将EmpService接口的实现类的实例
以及EmpDao接口的实现类的实例交给Spring容器创建,在核心配置文件中添加如下配置:
<?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">
<!-- 将EmpService接口的实现类的实例交给spring创建 -->
<bean id="empService" class="com.tc.service.EmpServiceImpl"></bean>
<!-- 将EmpDao接口的实现类的实例交给spring创建 -->
<bean id="empDao" class="com.tc.dao.EmpDaoImpl"></bean>
</beans>
创建测试类—TestSpring,通过spring的IOC解决程序中的耦合问题
2、测试步骤及代码如下:
public class TestSpring {
/**
* 使用spring的IOC解决程序中的耦合问题
*/
@Test
public void testIOC() {
//获取spring的核心容器对象
ApplicationContext ac =
new ClassPathXmlApplicationContext(
"applicationContext.xml");
//通过spring的核心容器获取EmpService接口的子类实例
EmpService service = (EmpService) ac.getBean("empService");
EmpDao dao = (EmpDao) ac.getBean("empDao");
System.out.println( service );
System.out.println( dao );
}
}
3、运行结果:
4、入门案例总结:
这就是spring框架的IOC——控制反转。之前我们自己new对象,例如:
User u = new User();
而现在,变成由一个初始化的xml配置文件来创建,也就是由spring容器来创建。
User user = (User) ac.getBean(“user”);
当程序运行,spring开始工作后,会加载整个xml核心配置文件,读取到,获取到class属性中类的全路径,利用反射创建该类的对象。