spring - 如何覆盖 dispatcherServlet 中的 contextConfigLocation

标签 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?

最佳答案

看起来您需要仔细查看您尝试覆盖的 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 方法(无需调用 super.init())。然后在调用 bw.setPropertyValues(pvs, true); 之前修改 pvs(您如何执行此操作)。

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

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

关于spring - 如何覆盖 dispatcherServlet 中的 contextConfigLocation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18098348/

相关文章:

java - 微服务和消息传递 : Message Content

java - Spring Autowired 组件在 bean 方法中为 null

java - 从输入区域返回空值

java - 获取 webapp 上下文的 URL(基本 URL)

eclipse - Eclipse 中的部署目录在哪里?

java - 模拟不与@Secured一起使用

java - 处理 OAuth2 回调时出现异常 (null)。 Spring Social Facebook 登录

session - 即使不存在 cookie,Tomcat 6 也会恢复 session

Tomcat 安全 key 警告

java - Tomcat 服务器上的 SSL 证书