码迷,mamicode.com
首页 > 移动开发 > 详细

Spring中ClassPathXmlApplication与FileSystemXmlApplicationContext的区别

时间:2018-01-13 15:38:54      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:equals   type   配置文件   多个   oid   ini   asc   log   文件   

一、概述

在项目中遇到加载不到Spring配置文件,简单分析后,写此文备忘!

二、测试所需资源

TestBean.java

public class TestBean {
    public TestBean(){
        System.out.println(this.getClass().getName().concat(" init !"));
    }

    public String getTestStr() {
        return "testStr";
    }
}

applicationContext.xml

<bean id="testBean" class="com.bean.TestBean" />

二、区别

2.1 ClassPathXmlApplicationContext使用方法

ClassPathXmlApplicationContext 默认会去 classPath 路径下找。classPath 路径指的就是编译后的 classes 目录。

示例:

@Test
public void testBean(){
    //单配置文件方式一
    BeanFactory beanFactory=new ClassPathXmlApplicationContext("applicationContext.xml");
    
    //单配置文件方式二
    BeanFactory beanFactory=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    
    //多个配置文件
    BeanFactory beanFactory=new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
    
    //绝对路径需加“file:”前缀
    BeanFactory beanFactory = new ClassPathXmlApplicationContext("file:E:\Workspace\idea_workspace\spring\springtest\src\main\resources\applicationContext.xml");

    TestBean bean= (TestBean) beanFactory.getBean("testBean");
    assertEquals("testStr",bean.getTestStr());
}

运行示例你会发现 “classpath:” 是可以缺省的。
如果是绝对路径,就需要加上 “file:” 前缀,不可缺省。

2.2 FileSystemXmlApplicationContext使用方法

FileSystemXmlApplicationContext 默认是去项目的路径下加载,可以是相对路径,也可以是绝对路径,若是绝对路径,“file:” 前缀可以缺省。

示例:

@Test
public void testBean(){
    //classes目录
    BeanFactory beanFactory=new FileSystemXmlApplicationContext("classpath:applicationContext.xml");

    //项目路径相对路径
    BeanFactory beanFactory=new FileSystemXmlApplicationContext("src\\main\\resources\\applicationContext.xml");

    //多配置文件
    BeanFactory beanFactory=new FileSystemXmlApplicationContext(new String[]{"src\\main\\resources\\applicationContext.xml"});

    //绝对目录
    BeanFactory beanFactory=new FileSystemXmlApplicationContext(new String[]{"E:\\Workspace\\idea_workspace\\spring\\springtest\\src\\main\\resources\\applicationContext.xml"});

    TestBean bean= (TestBean) beanFactory.getBean("testBean");
    assertEquals("testStr",bean.getTestStr());
}

Spring中ClassPathXmlApplication与FileSystemXmlApplicationContext的区别

标签:equals   type   配置文件   多个   oid   ini   asc   log   文件   

原文地址:https://www.cnblogs.com/sxc1991/p/8278917.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!