1、原因
不知不觉已经从事java开发好几年了,成了人们口中的老司机。但是一直都是恍恍惚惚过来,对于框架底层实现一直都没有怎么了解过,只是在面试的时候背些面试题。慢慢地发现不能这样,需要振作,笑~~~~。从这篇开始,记录自己对于Spring加载过程的源码查看。
2、开始
1、在Spring加载bean并获取bean定义的常用类是ClassPathXmlApplicationContext 以及AnnotationConfigApplicationContext。ClassPathXmlApplicationContext用来读取并加载默认classpath 路径下面的配置文件,AnnotationConfigApplicationContext是加载注解@Configuration标注的配置类。我现在关注于ClassPathXmlApplicationContext。
2、新建一个maven项目,并引入spring相关jar包。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
spring-boot-starter-we会依赖引入spring-context包,定义接口以及实现类
public interface Person {
void say();
}
@Log4j2
public class Teacher implements Person {
@Override
public void say() {
log.info("开始上课!");
}
}
编写bean.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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person" class="service.impl.Teacher"/>
</beans>
开始编写测试类用来测试bean加载过程:
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
Teacher teacher = (Teacher) applicationContext.getBean("person");
teacher.say();
}
第一行打上断点,debug开始跟着走,就会来到:
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException {
super(parent);
this.setConfigLocations(configLocations);
if (refresh) {
this.refresh();
}
}
点击this.refresh()方法进入就来到了最核心的地方,这里弄懂了,bean加载就弄懂了:
public void refresh() throws BeansException, IllegalStateException {
synchronized(this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
this.prepareRefresh();
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
try {
this.postProcessBeanFactory(beanFactory);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
this.invokeBeanFactoryPostProcessors(beanFactory);
this.registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
this.initMessageSource();
this.initApplicationEventMulticaster();
this.onRefresh();
this.registerListeners();
this.finishBeanFactoryInitialization(beanFactory);
this.finishRefresh();
} catch (BeansException var10) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var10);
}
this.destroyBeans();
this.cancelRefresh(var10);
throw var10;
} finally {
this.resetCommonCaches();
contextRefresh.end();
}
}
}
之后会慢慢开始学习这里!,新建公众号:随风的java开发人生,欢迎互关互助。