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

32 篇文章 15 订阅

今天想写一个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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值