Springboot的一个重要功能就是可以消除几乎所有的配置文件,使用JavaConfig取而代之。
而Servlet3.0以后也推崇实用注解的方式取代web.xml配置文件,为了实现这一目的,Springboot提供了对应的类。
- WebApplicationInitializer
- SpringServletContainerInitializer
首先看一下使用web.xml配置文件的方式,我们是如何启动SpringMVC的servlet:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
而实用JavaConfig的方式则是这样的:
public class MyWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
//实用xml的方式配置SpringMVC
XmlWebApplicationContext appContext = new XmlWebApplicationContext();
//设置配置文件的位置
appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
//将DispatcherServlet实例添加到容器
ServletRegistration.Dynamic dispatcher =
container.addServlet("dispatcher", new DispatcherServlet(appContext));
//设置启动顺序
dispatcher.setLoadOnStartup(1);
//设置映射路径
dispatcher.addMapping("/");
}
}
这样一来,就实现了通过注解启动Spring容器。
然而,这种配置方式虽然消除了web.xml配置文件,Spring的配置文件还是存在,为了进一步将Spring的配置文件切换为注解的配置方式,只需要将XmlWebApplicationContext换成AnnotationConfigApplicationContext。
public class MyWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
// 创建Spring的root配置环境
AnnotationConfigWebApplicationContext rootContext =
new AnnotationConfigWebApplicationContext();
rootContext.register(AppConfig.class);
// 将Spring的配置添加为listener
container.addListener(new ContextLoaderListener(rootContext));
// 创建SpringMVC的分发器
AnnotationConfigWebApplicationContext dispatcherContext =
new AnnotationConfigWebApplicationContext();
dispatcherContext.register(DispatcherConfig.class);
// 注册请求分发器
ServletRegistration.Dynamic dispatcher =
container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
通过以上的配置,就可以完全消除web应用中的配置文件,而以上方式其实也就是Springboot的使用方式。