我想覆盖上下文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()
)。然后在调用pvs
之前修改bw.setPropertyValues(pvs, true);
(执行此操作的方式)。或者在调用
initServletBean()
之前覆盖super.initServletBean()
并在此处修改属性。那就是我首先要尝试的:
或者,您尝试覆盖
getServletConfig()
,以便它返回修改后的配置。