1,spring 源码调试(5.1.12.RELEASE)----容器context
前言 : 关于本次涉及代码https://github.com/yunzhi98/springcontext.git
一,调试环境搭建:
1,maven3.4+jdk8
2,为了方便每一步的调试,所以直接用了main读取xml来调试进程。
public static void main(String[] args) {
AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext("crawlwab\\src\\main\\webapp\\application.xml");
UserService userService = (UserService)applicationContext.getBean("userService");
UserMapper userMapper = userService.getUserByName("xuyun");
System.out.println("-----------userService="+userMapper.getPassWord());
}
具体的xml配置,及测试用的bean代码,可以下载源码查看。
3,对于context抽象实现ClassPathXmlApplicationContext 先查看下他的继承关系,及每个继承抽象所实现的功能。
可以看到,
3.1 ClassPathXmlApplicationContext 是对xml解读来创建容器环境的,那我们具体去看下他提供了哪些方法。
private Resource[] configResources;
public ClassPathXmlApplicationContext() {
}
public ClassPathXmlApplicationContext(ApplicationContext parent) {
super(parent);
}
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[]{
configLocation}, true, (ApplicationContext)null);
}
public ClassPathXmlApplicationContext(String... configLocations) throws BeansException {
this(configLocations, true, (ApplicationContext)null);
}
public ClassPathXmlApplicationContext(String[] configLocations, @Nullable ApplicationContext parent) throws BeansException {
this(configLocations, true, parent);
}
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh) throws BeansException {
this(configLocations, refresh, (ApplicationContext)null);
}
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException {
super(parent);
this.setConfigLocations(configLocations);
if (refresh) {
this.refresh();
}
}
public ClassPathXmlApplicationContext(String path, Class<?> clazz) throws BeansException {
this(new String[]{
path}, clazz);
}
public ClassPathXmlApplicationContext(String[] paths, Class<?> clazz) throws BeansException {
this(paths, clazz, (ApplicationContext)null);
}
可以看到,都是创建的构造方法以及提供了一个对于容器内容的get方法。
protected Resource[] getConfigResources() {
return this.configResources;
}
我们用的是ClassPathXmlApplicationContext(String configLocation)方法做的测试,所以就看下这个构造方法的实现情况。
3.2 具体代码
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException {
super(parent);
this.setConfigLocations(configLocations);
if (refresh) {
this.refresh();
}
}
3.21 可以看到是先执行了个父类的 super(parent) 方法,传进去的是ApplicationContext对象