spring – 来自classpath资源的hibernate load * .hbm.xml
我在classpath资源中有一些hbm.xml文件位于src / main / resources maven的文件夹中。 我使用spring的LocalSessionFactoryBean使用以下bean配置加载这些文件:
mapping/SystemUser.hbm.xml mapping/SystemCredential.hbm.xml mapping/SystemProvince.hbm.xml hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
但它给了我FileNotFoundException。 请告诉我我做错了什么,谢谢。
当使用带有war
类型的项目的Maven时,位于src/main/resources
最终会出现在WEB-INF/classes
(并保留resources
目录结构)。 因此,要么将映射文件放在src/main/resources/mapping
要么使用以下配置:
SystemUser.hbm.xml SystemCredential.hbm.xml SystemProvince.hbm.xml
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
这看起来对我很好。 因此我不认为问题是配置。 我认为文件根本不在类路径上。 你是如何开始申请的?
如果您正在使用eclipse,请确保将src / main / resources用作源文件夹,并将资源复制到目标/类。
@Autowired private ResourceLoader rl; @Bean public LocalSessionFactoryBean sessionFactory() throws IOException { LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean(); sessionFactoryBean.setMappingLocations(loadResources()); } public Resource[] loadResources() { Resource[] resources = null; try { resources = ResourcePatternUtils.getResourcePatternResolver(rl) .getResources("classpath:/hibernate/*.hbm.xml"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return resources; }
在Web应用程序中,当您编写没有前缀的资源路径时,Spring会从上下文根(即,从包含WEB-INF的文件夹)加载它。 要从类路径加载资源,您应该使用“classpath:”前缀:
classpath:mapping/SystemUser.hbm.xml
如果从Web应用程序加载Spring应用程序上下文,您可能会看到如下错误:
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.io.FileNotFoundException: ServletContext resource [/hibernate.cfg.xml] cannot be resolved to URL because it does not exist
解决方案是明确告诉Spring从类路径加载配置,如下所示:
classpath:mypath/myfile.xml