• Spring中ClassPathXmlApplication与FileSystemXmlApplicationContext的区别


    Spring中ClassPathXmlApplication与FileSystemXmlApplicationContext的区别

    一、概述

    在项目中遇到加载不到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:Workspaceidea_workspacespringspringtestsrcmain
    esourcesapplicationContext.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());
    }
    
      注:文章中难免有不足之处,欢迎评论、互动、指正。

    作者: i-nine
    原创不易,本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    数据库连接池
    Apache- DBUtils框架学习
    权限表的设计
    Java的I/O对文件的操作
    Java下载文件
    Java连接MySQL数据库
    C#用log4net记录日志
    C#多线程和线程池
    C#利用反射动态调用DLL并返回结果,和获取程序集的信息
    CephRGW 在多个RGW负载均衡场景下,RGW 大文件并发分片上传功能验证
  • 原文地址:https://www.cnblogs.com/ninth/p/6841608.html
Copyright © 2020-2023  润新知