The DispatcherServlet, as any Servlet, needs to be declared and mapped according to the Servlet specification by using Java configuration or in web.xml. In turn, the DispatcherServlet uses Spring configuration to discover the delegate components it needs for request mapping, view resolution, exception handling, and more.
The following example of the Java configuration registers and initializes the DispatcherServlet, which is auto-detected by the Servlet container (see Servlet Config):
模拟springboot的源码实现
关键实现代码
```java public class MyWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletCxt) {
// Load Spring web application configuration
AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
ac.register(AppConfig.class);
ac.refresh();
// Create and register the DispatcherServlet
DispatcherServlet servlet = new DispatcherServlet(ac);
ServletRegistration.Dynamic registration = servletCxt.addServlet("app", servlet);
registration.setLoadOnStartup(1);
registration.addMapping("/app/*");
}
}
# spring mvc 正常初始化过程
1. web.xml
- ContextLoaderListener 声明一个DispatcherServlet
- spring init applicationContext.xml
- DispatcherServlet ap
2. applicationContext.xml
- 扫包 @Service @Component
3. spring-mvc.xml
- 扫包 @Controller
- 视图解析
- json解析器
# springboot如何做到零配置
springboot要做到零配置就要将上面1-3替换掉
- 替换ContextLoaderListener初始化 spring init
AnnotationConfigWebApplicationContext ac =
new AnnotationConfigWebApplicationContext();
- 替换 DispatcherServlet
DispatcherServlet servlet = new DispatcherServlet(ac);
ServletRegistration.Dynamic registration = servletCxt.addServlet("app", servlet);
addServlet 相当于
* 1,传统的web.xml
* <servlet>
* <servlet-class>sss</servlet-class>
* </servlet>
* 2 @WebServlet()
- 扫包
```java
@Configuration
@ComponentScan("com.example.springboot.*")
public class AppWebConfig implements WebMvcConfigurer {
}