Spring 框架源码解析:类加载过程原理
spring框架使用很广泛,既然使用很多,那么我们就应该对其了解,便于在工作中能更好的使用,遇到问题我们可以更快的排查,或者难道大家知道它是如何工作的吗?后续的几篇文章会介绍spring 加载xml并加载bean的过程,会有部分代码以及流程图,如有不对的地方大家还应该指出。
我们先上一段我们的测试代码:
public class TestService {
public static void main(String[] args) {
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("application.xml");
// 使用类型获取
SpringService service = app.getBean(SpringService.class);
// 使用类名获取
// SpringService service1 = (SpringService) app.getBean("springServiceImpl");
service.springServicePrint();
}
}
SpringService就是一个简单的接口:
public interface SpringService {
public String springServicePrint();
}
SpringService的实现类:SpringServiceImpl代码如下:
public String springServicePrint() {
String printStr = "测试";
System.out.println(printStr + " impl");
return printStr;
}
resources中增加application.xml配置文件(本实例中我们使用component-scan来扫描加载类),内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd"
default-autowire="byName">
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<context:component-scan base-package="com" />
</beans>
下面我们就开始看看整体流程:
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
super(parent);
// 配置xml文件路径
setConfigLocations(configLocations);
if (refresh) {
// 真正的加载逻辑方法(关键)
refresh();
}
}
- spring如何加载xml文件setConfigLocations