IOC(控制反转)解释
IOC Inverse of Control 反转控制的概念,就是将原本在程序中手动创建UserService对象的控制权,交由给Spring框架管理,简单说,就是创建UserService对象控制权被反转到了Spring框架。
DI(依赖注入)解释
Dependency Injection依赖注入,在Spring框架负责创建Bean对象时,动态的将依赖对象注入到Bean组件。
例子:在ApplicaionContext.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">
<!-- 配置一个bean【对象】 class 类的路径 -->
<bean id="userService" class="com.lq.service.impl.UserServiceImpl">
<!--依赖注入数据 调用属性的set方法 -->
<property name="name" value="zhangsan"></property>
</bean>
</beans>
在UserServiceImpl中增加一个属性name添加get/set方法
在Test测试类中
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
//2.从Spring容器获取UserService对象
UserService userService2 =(UserService)context.getBean("userService");
userService2.add();
UserService userService3 =(UserService)context.getBean("userService");
userService3.add();
System.out.println(userService2==userService3);
测试发现 Spring将属性为name的注入了有一个值为zhangsan 这就是依赖注入 通过set的方式 大家可以将其把service中set注释掉然后跑一次看看,程序会报错 就证明了。
下一篇:Spring的深入理解