您的位置:首页 > 编程语言 > Java开发

如何使用Javaconfig代替web.xml配置spring

2017-12-19 15:51 741 查看
我们知道使用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的配置文件位置


完成在这里已经完成了。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: