spring学习(十)--WebApplicationInitializer接口替代web.xml启动spring容器
Posted on 2019-10-24 10:16 GLLegolas 阅读(827) 评论(0) 收藏 举报对于Spring MVC的DispatcherServlet配置方式,传统的是基于XML方式的,也就是官方说明的XML-based,如下:
<!-- spring使用listener初始化bean(service和dao层bean) -->
<!-- contextConfigLocation指定上下文文件位置,该项配置为全局配置,
多个xml文件中间用逗号隔开,此项如果不配置,ContextLoaderListener默认取WEB-INF:applicationContext.xml -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springConfig/spring-beans.xml</param-value>
</context-param>
<!-- spring使用listener初始化bean(service和dao层bean) -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- spring使用servlet初始化bean(controller层bean) -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- init-param指定DispatcherServlet上下文配置文件的位置,为局部配置文件,只对DispatcherServlet有用
如果没有配置init-param,会默认读取/WEB-INF/${servlet-name}-servlet.xml -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springConfig/spring-all.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
但是Spring文档建议我们采用code-based这种方式,当然,核心就是实现WebApplicationInitializer这个接口,查看这个接口的源码,里面也非常简单,只有一个方法onStartup,传入的参数是ServletContext。onStartup方法会随着web容器启动而被调用,我们在onStartup方法中实现自己的spring配置文件加载,不用在web.xml文件中配置listener和dispatchServlet,也可以启动spring容器。
1、将上述web.xml中的spring初始化监听器和servlet配置去掉,此时web容器在启动的时候,并不会加载spring,spring的bean也不会被初始化。
2、编写spring启动类实现WebApplicationInitializer接口,重写onStartup方法:
package serviceImpl; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.XmlWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; public class SpringBeanInitializer implements WebApplicationInitializer{ @Override public void onStartup(ServletContext servletContext) throws ServletException { XmlWebApplicationContext appContext = new XmlWebApplicationContext(); appContext.setConfigLocation("classpath:springConfig/spring-all.xml"); ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(appContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); } }
此时,启动web容器,spring会被启动,spring-all.xml中配置的bean都会被初始化。至此,可以去掉web.xml中的spring启动配置,通过实现WebApplicationInitializer类,启动spring容器。
其中ServletRegistration类,需要引入3.0以上版本的servlet-api包。
<properties>
<servlet-api.version>3.0.1</servlet-api.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet-api.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
个人理解,如有错误,欢迎指正!
浙公网安备 33010602011771号