首先说下场景:一个父工程maven_parent,下面三个子工程:maven_web、maven_service、maven_dao,从左到右依次依赖。Spring管理hibernate,把实体类放到了dao中,把applicationContext放在了web中。
照成的结果就是运行parent工程没问题,但是运行web项目的时候报错
查看了一下applicationContext,发现这么一行
<property name="mappingDirectoryLocations" value="classpath:cn/itcast/entity"></property>
//这是它的源码,发现它会去匹配value值是不是一个文件夹,如果不是会抛出异常
if (this.mappingDirectoryLocations != null) {
// Register all Hibernate mapping definitions in the given directories.
for (Resource resource : this.mappingDirectoryLocations) {
File file = resource.getFile();
if (!file.isDirectory()) {
throw new IllegalArgumentException(
"Mapping directory location [" + resource + "] does not denote a directory");
}
sfb.addDirectory(file);
}
}
原来是它照成。接下来是我的猜想,但是无法找到源码论证:
1、Spring为hibernate准备了四种映射方式,分别匹配的是文件夹,jar,全路径,配置文件名
详细介绍请跳转:点击打开链接
2、web模块依赖了service模块,service模块依赖了dao模块,如果运行web模块的话,那么他在运行之前要先把service和dao打包,即便在同一个项目中,虽然编译的时候同一个项目引用文件夹没关系,但是如果运行的时候他还是要打包的。所以如果文件夹匹配的话,由于是jar,不是文件夹,会抛异常。
3、运行parent工程的话,他统一构建会把运用到的子模块都拷贝到自己的项目中,从而构成一个完整项目,而且子模块的目录结构都是固定的,所以构建结果是和自己创建项目(不用maven创建)一样的。所以在classPath中可以找到对应的文件夹。