关于springMVC中继承AbstractAnnotationConfigDispatcherServletInitializer用于初始化DispatcherServlet的类,之前一直不明白其getRootConfigClasses和getServletConfigClasses方法的参数是怎么驱动配置的,测试了一下之后发现了原理。
工程结构和代码如下图
Application 代码:
package test.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
@Configuration
@ComponentScan(basePackages=Application.CONFIG_PACKAGE)
public class Application extends AbstractAnnotationConfigDispatcherServletInitializer{
public static final String CONFIG_PACKAGE="test.config";
// 应用上下文,除web部分
@Override
protected Class<?>[] getRootConfigClasses() {
System.err.println("getRootConfigClasses");
return new Class[]{ApplicationConfig.class};
}
//web部分,配置dispatcher servlet,如果在root config指定了该转发规则就可以忽略
@Override
protected Class<?>[] getServletConfigClasses() {
System.err.println("getServletConfigClasses");
return new Class[]{};
}
//指定开始被servlet处理的url,配置从/开始
@Override
protected String[] getServletMappings() {
System.err.println("getServletMappings");
return new String[]{"/"};
}
//将相关的组件注册到服务器
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
System.err.println("onStartup");
servletContext.addListener(RequestContextListener.class);
super.onStartup(servletContext);
}
@Override
protected void customizeRegistration(Dynamic registration) {
System.err.println("customizeRegistration");
registration.setInitParameter("dispatchOptionsRequest", "true");
}
}
<span style="font-size:14px;">@Configuration
@ComponentScan(basePackages = ApplicationConfig.PACKAGE_NAMESPACE)
public class ApplicationConfig {
public static final String PACKAGE_NAMESPACE="test";
}</span>
其中Application类相当于applicationcontext.xml,如果他的@ComponentScan配置的是整个工程的话,那么getRootConfigClasses方法的参数传他自己就行了,因为整个工程中的配置文件都会被他扫描到。