微观:将学习的 Spring SpringMVC Mybatis 框架应用到项目中!
宏观:Spring 接管一切(将框架核心组件交给 Spring 进行 IoC 管理),代码更加简洁。
实施:通过编写配置文件,实现 SpringIoC 容器接管一切组件。

| 容器名 | 盛放组件 |
|---|---|
| web 容器 | web 相关组件(controller,springmvc 核心组件) |
| root 容器 | 业务和持久层相关组件(service,aop,tx,dataSource,mybatis,mapper 等) |


protected WebApplicationContext createWebApplicationContext(@Nullable ApplicationContext parent) {
Class<?> contextClass = getContextClass();
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException(
"Fatal initialization error in servlet with name '" + getServletName() +
"': custom WebApplicationContext class [" + contextClass.getName() +
"] is not of type ConfigurableWebApplicationContext");
}
ConfigurableWebApplicationContext wac =
(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
wac.setEnvironment(getEnvironment());
//wac 就是web ioc容器
//parent 就是root ioc容器
//web容器设置root容器为父容器,所以web容器可以引用root容器
wac.setParent(parent);
String configLocation = getContextConfigLocation();
if (configLocation != null) {
wac.setConfigLocation(configLocation);
}
configureAndRefreshWebApplicationContext(wac);
return wac;
}


| 配置名 | 对应内容 | 对应容器 |
|---|---|---|
| WebJavaConfig | controller,springmvc 相关 | web 容器 |
| ServiceJavaConfig | service,aop,tx 相关 | root 容器 |
| MapperJavaConfig | mapper,datasource,mybatis 相关 | root 容器 |
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
//指定root容器对应的配置类
//root容器的配置类
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { ServiceJavaConfig.class,MapperJavaConfig.class };
}
//指定web容器对应的配置类 webioc容器的配置类
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebJavaConfig.class };
}
//指定dispatcherServlet处理路径,通常为 /
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
