0

我想覆盖上下文 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?

4

1 回答 1

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(),以便它返回您修改后的配置。

于 2013-08-07T10:40:03.453 回答