我们知道使用spring时候最让人烦的是大量的xml配置文件。在使用spring框架时候在web.xml中配置spring传统配置是:<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置加载任意目录下的任意的xml文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext_*.xml</param-value>
</context-param>
配置springmvc:
<servlet>
<servlet-name>Spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 指定springmvc的配置文件的位置与名字 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
使用javaconfig配置:
第一步:定义一个类实现WebApplicationInitializer接口 实现onStartup方法
编写:
public void onStartup(ServletContext servletContext) throws ServletException {
//配置spring
servletContext.setInitParameter("contextConfigLocation","classpath:applicationContext_1.xml");
servletContext.addListener(new ContextLoaderListener());
//配置springmvc
ServletRegistration.Dynamic springMVC= servletContext.addServlet("spring",new DispatcherServlet());//加载springMVC核心类
springMVC.addMapping("/");
springMVC.setInitParameter("contextConfigLocation","classpath:servlet.xml");//设置springmvc的配置文件位置
完成在这里已经完成了。