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