如何使用Javaconfig代替web.xml配置spring
我們知道使用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的配置檔案位置
完成在這裡已經完成了。