0X0b IOC容器
1、IOC概念和原理
(1)控制和反转,把对象创建和对象之间的调用,交给Spring进行管理
(2)使用IOC的目的:为了耦合度降低
IOC底层原理
XML解析、工厂模式、反射
IOC接口
(1)BeanFactory:IOC容器的基本实现,是Spring内部直接使用,不提供给开发人员使用
加载配置文件的时候不会创建对象,只有在使用的时候才创建对象
(2)ApplicationContext:BeanFactory的子接口,比BeanFactory功能更强大,提供给开发人员使用
在加载了配置文件的时候就已经创建了对象
接口有实现类
FileSystemXmlApplicationContext,后面写的文件路径必须为系统路径
ClassPathXmlApplicationContext,后面写的文件路径为src下的路径
2、IOC操作Bean管理
什么是Bean管理
Spring创建对象和Spring注入属性
基于xml的bean管理
1、基于xml方式创建对象
<bean id="user" class="com.company.User"></bean>
(1)在Spring配置文件中,使用bean标签,标签里面添加对应属性,就可以实现对象创建
(2)在bean标签有很多属性,常用的属性
* id:唯一标识
* class:类全路径(包类路径)
(3)创建对象时,默认执行无参数构造方法
基于XML方式注入属性
(1)DI:依赖注入,就是注入属性
set方法注入或者有参构造注入
(2)在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">
<bean id="user" class="com.company.User">
<constructor-arg name="name" value="hello"></constructor-arg>
<constructor-arg name="password" value="world"></constructor-arg>
</bean>
</beans>
package com.company;
public class User {
private String name;
private String password;
User(String name, String password){
this.name = name;
this.password = password;
}
public void print() {
System.out.println(name + ' ' + password);
}
}
package com.company;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("bean1.xml");
User user = context.getBean("user", User.class);
System.out.println(user);
user.print();
}
}