同时加载mvc-dispatcher-servlet.xml和applicationContext.xml文件?

11 浏览
0 Comments

同时加载mvc-dispatcher-servlet.xml和applicationContext.xml文件?

我正在使用Spring 3 MVC。

我有mvc-dispatcher-servlet.xml和applicationContext.xml两个文件。

但是只有mvc-dispatcher-servlet.xml加载了,applicationContext.xml没有加载。

我的配置有什么问题吗?

web.xml

  
  Archetype Created Web Application
    
        mvc-dispatcher  
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:spring/mvc-dispatcher-servlet.xml
           
        1  
      
      
        mvc-dispatcher  
        *.do  
    
      
        contextConfigLocation  
        classpath:spring/extendedContext.xml  
      
      
        org.springframework.web.context.ContextLoaderListener  
      

0
0 Comments

问题的出现原因:在Spring MVC项目中,我们通常会使用一个mvc-dispatcher-servlet.xml文件来配置DispatcherServlet,并使用一个applicationContext.xml文件来配置其他的bean。然而,在某些情况下,我们可能需要同时加载这两个配置文件。

解决方法:一种解决方法是使用ContextLoader来加载所有的配置文件,可以通过在web.xml文件中的contextConfigLocation参数中指定多个配置文件的路径,使用逗号进行分隔。

以下是解决方法的示例代码:

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/mvc-dispatcher-servlet.xml, 
                 classpath:spring/applicationContext.xml,
                 classpath:spring/extendedContext.xml
    </param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app>

以上代码中,我们通过在contextConfigLocation参数中指定了mvc-dispatcher-servlet.xml、applicationContext.xml和extendedContext.xml三个配置文件的路径,使用逗号进行分隔。

这样,当应用程序启动时,ContextLoaderListener将加载所有的配置文件,并将它们合并成一个应用程序上下文,使得mvc-dispatcher-servlet.xml和applicationContext.xml中的bean都可以被应用程序访问到。

0
0 Comments

问题的原因是希望在Spring的dispatcher servlet XML文件中同时加载mvc-dispatcher-servlet.xml和applicationContext.xml。这个问题的解决方法是使用"import"标签在dispatcher servlet XML文件中导入applicationContext.xml。通过这种方式,不需要使用ContextLoaderListener来加载ApplicationContext。如果想要使用ContextLoaderListener解决一些特定问题,可以使用标签在web.xml文件中配置参数,然后在ContextLoaderListener中进行处理。如果不想使用ContextLoaderListener,还可以使用标签来管理属性文件,通过创建符号链接或使用环境变量来解决不同环境下的属性文件名问题。

总结一下,解决问题的方法是在dispatcher servlet XML文件中使用"import"标签导入其他XML配置文件,而不是通过ContextLoaderListener来加载ApplicationContext。如果有特殊需求,可以使用标签来管理属性文件。

0