Spring加载配置文件
2016-02-23 18:22
369 查看
最近在看《Spring3.0就这么简单》这本书,开发环境为IDEA+Maven,今儿写代码时,Spring加载配置文件总是失败,相当郁闷,不过还是解决了。最初的写法是
Resource res=new ClassPathResource("classpath:com/smart/beanfactory/beans.xml");
或者
ApplicationContext factory = new ClassPathXmlApplicationContext("beans.xml");
当然,括号里的路径诸如直接写beans.xml,或在前面加路径,或加classpath,或将beans.xml换在src、main、java等目录下,改了好多次,运行结果均是找不到配置文件。目录结构如下:
解决方案:将配置文件放在resources目录下,这是Maven项目放置配置文件的专用目录。附ApplicationContext的初始化:1、配置文件在类路径,优先使用ClassPathXMLApplicationContext: ApplicationContext ctx=new ClassPathXmlApplicationContext("com/smart/context/beans.xml");对于ClassPathXMLApplicationContext,"com/smart/context/beans.xml"等同于"classpath:com/smart/context/beans.xml"2、配置文件在文件系统路径,优先使用FileSystemXMLApplicationContextApplicationContext ctx=new FileSystemXMLApplicationContext("com/smart/context/beans.xml");"com/smart/context/beans.xml"等同于"file:com/smart/context/beans.xml"3、配置文件整合 Spring会自动将多个配置文件在内存中“整合”成一个配置文件。new ClassPathXMLApplicationContext(new String[] {"conf/beans1.xml","conf/beans2.xml"})FileSystem~和ClassPath~都可显示使用带资源类型前缀的路径。区别:如果不显示指定资源类型前缀,就分别将路径解析为文件系统路径和类路径。相关代码:可访问我的github的chapter仓库chapter2目录。
欢迎个人转载,但须在文章页面明显位置给出原文连接;未经作者同意必须保留此段声明、不得随意修改原文、不得用于商业用途,否则保留追究法律责任的权利。【 CSDN 】:csdn.zxiaofan.com【GitHub】:github.zxiaofan.com如有任何问题,欢迎留言。祝君好运!Life is all about choices!将来的你一定会感激现在拼命的自己!
相关文章推荐
- Java回调机制与OOP思想
- org.springframework.web.context.ContextLoaderListener找不到的解决方法
- struts向jsp页面传值
- Eclipse 搭建Struts2
- java动态控制线程的启动和停止
- 基于Spring + Spring MVC + Mybatis + shiro 高性能web构建
- java序列化和json序列化效率对比
- java 嵌套遍历文件夹里面的文件和文件夹
- SpringMVC传值
- Promise模式简介(Future) --- Java实现异步
- Java线程
- Java定时执行任务
- java学习笔记-代码块
- Java中 Map、Set、List
- maven 常用命令 mvn 发布可执行jar包
- Java Reflection(十二):动态类加载与重载
- java基本语法
- Java解析JSON
- Java Reflection(十一):动态代理
- Java 回顾笔记6(晚上)