IOC的本质
控制反转是一种设计思想,没有IOC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所有的控制反转就是:获得依赖对象的方式反转了。
通过接口去调用,解耦对象与对象之间的强联系
public class UserserviceImpl implements UserService{
private UserDao userDao;
public void setUserDao(UserDao userDao){
this,userDao=userDao;
}
}
IOC容器的实现方式是DI依赖注入
本质上是使用set方法来进行注入的,所以对应的类属性一定要有set方法
Spring中Bean对象的创建过程
1、bean指的什么
bean 代表一个对象
在这里插入代码片<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDao" class="com.user.UserDao">
<property name="str" value="spring">
</bean>
</beans>
2、Spring是怎么创建bean的
通过配置文件,创建IOC容器,创建对象,id=变量名,class为new 的对象 ,property相当于给对象属性设置一个指
3、bean中属性是怎么设置的
bean中的属性是由Sping创建的,前提是对象属性有set方法
一些概念
1、bean的Spring创建过程就是控制反转
2、控制是指谁来控制对象的创建,传统程序对象是由程序本身创建的,使用spring后,对象是由Spring创建的
3、反转:程序本身不创建对象,而变成被动的创建对象
4、依赖注入:就是利用set方法来进行注入,是IOC的实现方式之一
5、所谓的IOC:是指对象由spring来创建,管理和装配
注意:可以通过查看ApplicationContext去浏览底层代码,ApplicationContext的实现类ClassPathXmlApplicationContext是xml配置bean的处理类,其他的Annotation是spring注解版本的IOC容器的处理,本质还是使用注解+反射实现bean的创建