- 准备工作
- 创建一个springboot或者maven项目并添加spring依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 准备一个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-4.0.xsd
">
<bean id="user" class="com.example.demo.User">
<property name="name" value="张三"></property>
<property name="pwd" value="123"></property>
</bean>
<bean id="myBeanFactoryPostProcessor" class="com.example.demo.MyBeanFactoryPostProcessor"></bean>
</beans>
- 写些代码
public static void main(String[] args) {
// SpringApplication.run(DemoApplication.class, args);
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
Object user = applicationContext.getBean("user");
System.out.println(user);
}
- 了解大致机制
通过统一的接口规范读取xml文件或者注解的信息,生成beanDefintion信息,同时通过BeanFactoryPostProcessor获取完整的BeanDefintion信息(可以自己定义BeanFactoryPostProcessor到达一些目的),拥有完整的BeanDefintion信息后就可以通过反射获取到bean对象并进行使用了
- 跟源码学习
ClassPathXmlApplicationContext("bean.xml");
主要入口
准备在此上下文中使用的bean工厂。
prepareBeanFactory(beanFactory);
后置处理器:可以实现BeanFactoryPostProcessor接口的postProcessBeanFactory方法来达到自己想要的目的
postProcessBeanFactory(beanFactory);
实例化所有BeanFactoryPostProcessor的实例并且执行postProcessBeanFactory方法。
invokeBeanFactoryPostProcessors(beanFactory);