BeanFactory容器是Spring的一个重要的容器,后面所有的容器都是继承了这个容器;其中BeanFactory一个重要的实现类是DefaultListableBeanFactory。
BeanFactory容器的初始化过程如下
- 设置一个抽象资源,用于定位我们Bean定义的资源处,这里我们采用ClasspathResource定位资源,其实ClasspathResource这个资源的主要有两个属性,一个是path,另一个就是file,path指定文件的位置,置用java.io.File这个类将path指定将指定的配置文件的位置连接起来。
- 新建一个BeanFactory用于保存BeanDefinition,这里我们用BeanFactory的一个实现类DefaultListableBeanFactory。
- 新建一个XmlBeanFactoryReader用于将ClasspathResource读取Bean definition,这样我们
- 调用XmlBeanFactoryReader中的loadBeanDefinition方法将读取到的信息注入到BeanFactory中。
案例
package com.zbt.springbean_day01;
/**
* Created by luckyboy on 2018/8/18.
*/
public class Student {
private int age;
private String name;
public Student(){}
public Student(int age,String name){
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
spring-config.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="student" class="com.zbt.springbean_day01.Student">
<property name="age" value="10"></property>
<property name="name" value="Zou"></property>
</bean>
</beans>
测试文件
@Test
public void test2(){
//1、建立抽象资源的位置
ClassPathResource resource = new ClassPathResource("contextConfig.xml");
//2、创建一个IOC容器
DefaultListableBeanFactory container = new DefaultListableBeanFactory();
//3、将建立一个载入BeanDefinition的读取器用于读取BeanDefinition的信息,这里使用XmlBeanDefinitionReader读取资源
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(container);
//4、读取抽象资源
reader.loadBeanDefinitions(resource);
Student stu = (Student) container.getBean("student");
System.out.println(stu.getName());
}