您的位置:首页 > 编程语言 > Java开发

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!将来的你一定会感激现在拼命的自己!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: