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

我们知道使用spring时候最让人烦的是大量的xml配置文件。在使用spring框架时候在web.xml中配置spring传统配置是:
  org.springframework.web.context.ContextLoaderListener
 


  
contextConfigLocation
classpath:applicationContext_*.xml


配置springmvc:


      Spring
      org.springframework.web.servlet.DispatcherServlet

  
        contextConfigLocation
        classpath:spring-servlet.xml  
        

  
    1
 

 
      Spring
      /
 

使用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的配置文件位置

完成在这里已经完成了。



你可能感兴趣的:(如何使用Javaconfig代替web.xml配置spring)