SpringMVC-part2
首先對昨天的問題加以補充,今天空餘時間查詢了springmvc的參考文檔及api,發現以下幾個重要的地方
1
Below is an example of the Java configuration that registers and initializes the
DispatcherServlet.This class is auto-detected by the Servlet container (see Servlet Config):
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/*");
}
}
2
In addition to using the ServletContext API directly, you can also extend AbstractAnnotationConfigDispatcherServletInitializer and override specific methods (see example under Context Hierarchy).
Below is example configuration with a WebApplicationContext hierarchy:
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?[] { RootConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?[] { App1Config.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/app1/*" };
}
}
可以看到,第二部分即爲我們昨天配置的dispatcherservlet初始化方法。在參考文檔中很明確的說明了,spring的初始化入口爲WebApplicationInitializer,但其內部實現了一個簡單的AbstractAnnotationConfigDispatcherServeltInitializer。我們只需要重寫三個接口就行。
3
AbstractAnnotationConfigDispatcherServletInitializer
看一下spring官方api
其實springmvc只需要重寫兩個類。
- getRootConfigClasses() –
- getServletConfigClasses() –
其實getRootConfigClasses和getServletConfigClass並沒有什麼不一樣,只是習慣性的在兩個配置文件中放入不同的配置信息,至於到底有哪些不一樣的地方,我還不明白。
4
寫的太亂了點,當作自己筆記吧,下一章明確一下註解的作用。
@configuration
@component
@componentScan
@Bean