springboot
springboot 笔记
spring-mvc 官方文档
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 扫包功能 因为已经实现了@Controller的扫包功能,只需将ac配置到声明的DDispatcherServlet 中就可以实现
springboot如何内嵌容器的
tomcat 是有java语言编写的,所以可以直接在java程序中声明一个Tomcat
但是tomcat 为啥回去执行MyWebApplicationInitializer类下的onStartup方法呢?
这里涉及到servlet 3.0 的规范:
出现这个错误是因为tomcat.addwebapp()默认认为你为加载jsp,org.apache.jasper.servlet.JspServlet 将其改为 tomcat.addContext() 将会出现 MyWebApplicationInitializer类下onstartup()方法 不会自动执行
改为手动执行
```java public class SpringApplication { public static void run() throws LifecycleException { Tomcat tomcat = new Tomcat(); tomcat.setPort(9898); // tomcat.addContext("/",""); tomcat.addWebapp("/","");
}
在AppWebConfig加上注解@EnableWebMvc并实现WebMvcConfigurer
@EnableWebMvc会使得spring在初始化时会调用
Last updated
Was this helpful?