Spring加载配置文件

来源:互联网 发布:c语言输入3个数排序 编辑:程序博客网 时间:2024/06/06 07:38

        最近在看《Spring3.0就这么简单》这本书,开发环境为IDEA+Maven,今儿写代码时,Spring加载配置文件总是失败,相当郁闷,不过还是解决了。

最初的写法是

 Resource res=new ClassPathResource("classpathcom/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、配置文件在文件系统路径,优先使用FileSystemXMLApplicationContext
ApplicationContext 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目录。


1 0
原创粉丝点击