spring是一个很有名的java开源框架,作为一名javaer还是有必要了解spring的设计原理和机制,beans、core、context作为spring的三个核心组件。而三个组件中最重要的就是beans组件了。
从一个简单实例来查看spring加载配置文件中的bean。
public class Student { private int stId; private String studentName; private String studentAge; public int getStId() { return stId; } public void setStId(int stId) { this.stId = stId; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public String getStudentAge() { return studentAge; } public void setStudentAge(String studentAge) { this.studentAge = studentAge; } }
spring-beans.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:mvc="http://www.springframework.org/schema/mvc" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="student" class="org.lzyer.test.Student"></bean> </beans>
测试类
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({ "classpath:spring/spring-beans.xml"}) public class SpringSourceTest { @Test public void testSpring1(){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/spring-beans.xml"); Student student = (Student)context.getBean("student"); System.out.println(student); } }
spring配置文件加载流程
(点击查看大图)
下面对每一个流程的代码展示
刷新context
获取beanFactory
刷新beanFacory
获取配置文件,并且加载beanDefinition
读取配置文件
解析xml文件
解析beanDefinition
注册beanDefinition
最后将beanDefinition注册到beanDefinitionMap中