如何在dispatcherServlet中覆盖contextConfigLocation

时间:2013-08-07 08:26:55

标签: spring tomcat servlets

我想覆盖上下文configLocation

web.xml如下

<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>com.mypackage.MyDispacherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:default-ctx.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

然后是MyDispacherServlet

public class MyDispacherServlet extends org.springframework.web.servlet.DispatcherServlet {


@Override
public void init(ServletConfig config) throws ServletException {
    // here will be code to find dynamically other-ctx.xml
    String correctSpringXml = "classpath*:other-ctx.xml";
    setContextConfigLocation(correctSpringXml) ;
    super.init(config);
}

@Override
protected WebApplicationContext initWebApplicationContext() throws BeansException {
    WebApplicationContext wac = super.initWebApplicationContext();

    return wac;
}

}

但是这段代码不起作用。 如何才能正确覆盖contextConfigLocation?

1 个答案:

答案 0 :(得分:1)

看起来您需要仔细查看您尝试覆盖的init方法(在HttpServletBean中定义)。

//unimportent parts removed
    @Override
    public final void init() throws ServletException {
            ...
        try {
            PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
            BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
            ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
            bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, this.environment));
            initBeanWrapper(bw);
            bw.setPropertyValues(pvs, true);
        }
        catch (BeansException ex) {...}
            ...
        // Let subclasses do whatever initialization they like.
        initServletBean();
            ...
    }

看起来contextConfigLocation

设置了bw.setPropertyValues(pvs, true);参数

解决方案的不同想法:

  • 您需要覆盖init方法complete(不调用super.init())。然后在调用pvs之前修改bw.setPropertyValues(pvs, true);(如何执行此操作)。

  • 或者在调用initServletBean()之前覆盖super.initServletBean()并修改其中的属性。

  • 这是我首先尝试的方法: 或者您尝试覆盖getServletConfig(),以便它返回您的修改配置。