tomcat如何載入自己寫的類AppWebInitializer?
阿新 • • 發佈:2018-12-28
package com.db.common.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class AppWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { //載入model @Override protected Class<?>[] getRootConfigClasses() { System.out.println("getRootConfigClasses"); return new Class[]{AppRootConfig.class}; } //官方建議在此方法中載入View,Controller @Override protected Class<?>[] getServletConfigClasses() { System.out.println("getServletConfigClasses"); return new Class[]{AppMvcConfig.class}; } //定義請求對映 @Override protected String[] getServletMappings() { System.out.println("getServletMappings"); return new String[]{"*.do"}; } }
為什麼自己寫的AppWebInitializer類繼承了AbstractAnnotationConfigDispatcherServletInitializer就會被載入呢?這是Servlet3.0之後的規範,會自動讀取。載入javax.servlet.ServletContainerInitializer檔案中的類。由tomcat構建檔案中類的物件 ,並呼叫onStartup方法。spring中就是這樣玩的。
spring的SpringServletContainerInitializer上面的註解@HandlesTypes(WebApplicationInitializer.class),會把WebApplicationInitializer.class和WebApplicationInitializer.class的子類傳遞給onStartup方法