0
点赞
收藏
分享

微信扫一扫

【SpringMVC(十一)】xml默认配置文件位置


今天想写一个springmvc的demo程序,但是一直在报找不到applicationContext.xml配置文件的错误。我当时将配置文件放在了classpath下,以为spring启动时默认是在classpath下寻找的,但是实际上不是,这里做一个记录。

如果使用xml配置方式,那么默认会使用XmlWebApplicationContext类型的容器。

该容器实现了loadBeanDefinition方法:

protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws IOException {
String[] configLocations = getConfigLocations();
if (configLocations != null) {
for (String configLocation : configLocations) {
reader.loadBeanDefinitions(configLocation);
}
}
}

这个方法会加载bean,从configLocation处加载,下面看下这个getConfigLocations方法:

protected String[] getConfigLocations() {
return (this.configLocations != null ? this.configLocations : getDefaultConfigLocations());
}

如果没有显示指定,默认走default:

@Override
protected String[] getDefaultConfigLocations() {
if (getNamespace() != null) {
return new String[] {DEFAULT_CONFIG_LOCATION_PREFIX + getNamespace() + DEFAULT_CONFIG_LOCATION_SUFFIX};
}
else {
return new String[] {DEFAULT_CONFIG_LOCATION};
}
}

如果namespace不为空,说明这是servlet子容器,dispatcherServlet在启动时会将servlet的名字设置为这个namespace。看下dispatcherServlet如何设置这个namespace的:

public String getNamespace() {
return (this.namespace != null ? this.namespace : getServletName() + DEFAULT_NAMESPACE_SUFFIX);
}
public static final String DEFAULT_NAMESPACE_SUFFIX = "-servlet";

如果没有显示指定,就是${servletname}-servlet。

如果namesapce为空,那么就是父容器。

贴一下getConfigLocation里的几个常量:
 

/** Default config location for the root context */
public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml";

/** Default prefix for building a config location for a namespace */
public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/";

/** Default suffix for building a config location for a namespace */
public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".xml";

所以,

父容器的默认配置路径:/WEB-INF/appcalitionContext.xml

子容器的默认配置路径:/WEB-INF/${servletName}-servlet.xml

也就是说,默认位置找/WEB-INF目录下的配置文件。

举报

相关推荐

0 条评论