java中读取配置文件的方法fileSystemXmlapplicationContext与classPathXmlApplicationContext

java中读取配置文件的方法fileSystemXmlapplicationContext与classPathXmlApplicationContext

文章转自:http://blog.csdn.net/stypace/article/details/38414871 点击打开链接  


一、使用org.apache.commons.configuration

需要使用的是jar包:commons-collections-3.2.1.jar、commons-configuration-1.10.jar、commons-lang-2.6.jar和commons-logging-1.2.jar。

可以读取的配置文件:xml和properties

1、读取xml文件

import org.apache.commons.configuration.Configuration;  
import org.apache.commons.configuration.ConfigurationException;  
import org.apache.commons.configuration.XMLConfiguration;  
public class xmlLoaderTest {  
  
    public static void main(String[] args) throws ConfigurationException{  
       Configuration config = new XMLConfiguration("com/styspace/config.xml");  
       String name = config.getString("Account.name");  
       System.out.println("name:" + name);  
    }  
}  

需要注意的是config.getString(“Account.name”)中的参数是Account.name,这个参数是XPath格式的,而且不能包含xml中的根元素。

使用到的config.xml内容如下:

<Accounts>   
    <Account type="by0003">    
        <code>100001</code>   
        <pass>123</pass>   
        <name>李四</name>    
        <money>1000000.00</money>    
    </Account>    

2、读取properties文件

import org.apache.commons.configuration.Configuration;  
import org.apache.commons.configuration.ConfigurationException;  
import org.apache.commons.configuration.PropertiesConfiguration;  
  
public class peropertiesLoaderTest {  
  
    public static void main(String[] args) throws ConfigurationException{  
       Configuration config = new PropertiesConfiguration("com/styspace/config.properties");  
       String name = config.getString("name");  
       System.out.println("name:" + name);  
    }  
}  

使用到的config.properties文件内容如下

timout=15.52  
interactive=true  
color=red  
speed=50  
name=Default User

二、使用java.util.Properties读取

方法一

FileInputStream is=new FileInputStream("E:/eclipse/springMVC2/resource/db-config.properties");
		Properties properties=new Properties();
		properties.load(is);
		System.out.println(properties.getProperty("db.url"));

方法二

public class test {
	public static void main(String args[]) throws IOException{
                //相对路径
		test t=new test();
		t.bd();
private  void bd() throws IOException {
		//getClassLoader()方法默认查找src目录下的文件
		InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db-config.properties");  
		 Properties properties=new Properties();
		 properties.load(inputStream);
		 System.out.println(properties.getProperty("db.username"));
	}

}

目录图:

java中读取配置文件的方法fileSystemXmlapplicationContext与classPathXmlApplicationContext


需要注意的是hetClassLoader().getResourceAsStream()的参数是项目根目录下的路径,尽管config.properties是该该类文件在相同的目录下,但是不能写成getClassLoader().getResourceAsStream(“config.properties”),这样程序会报错,得到的InputStream是null值。


ClassLoader()和URLClassLoader()区别:ClassLoader()只能查找src目录下的文件,而URLClassLoader()则能查找任意目录下的文件。

三、spring中配置文件的读取

1、ClassPathXmlApplicationContext:从类路径中加载。

2、FileSystemXmlApplicationContext:从文件系统加载。

3、XmlWebApplicationContext:web系统中加载。

1、使用bean工厂获取bean

ClassPathResource resource = new ClassPathResource("spring.xml");//类路径  
    factory= new XmlBeanFactory(resource);   
      
    FileSystemResource fileSystemResource = new FileSystemResource("D:\\Ncode\\mcode\\sday02\\src\\spring.xml");//文件路径  
    factory= new XmlBeanFactory(fileSystemResource);   
      
    //XmlBeanFactory(参数可以是resource或者fileSystemResource等  
    //但是不能是 res 原因可以查看:文档Part III. Core Technologies 6. Resources  
    //中6.2 The Resource interface 有关isOpen方法的说明);  
    //InputStreamResource res = new InputStreamResource(new FileInputStream("D:\\Ncode\\mcode\\sday02\\src\\spring.xml"));//系统路径  
  
    HelloService helloService = factory.getBean("helloServiceImpl", HelloServiceImpl.class);  
    helloService.sayHello();


2、使用上下文(Context)

上下文更加高级:提供文本信息解析工具,包括对国际化支持;提供载入文件资源的通用方法,如图片;可以向注册为监听器的bean发送事件。

 在很少的情况下,使用BeanFactory。

pplicationContext context = new FileSystemXmlApplicationContext("file:D:\\Ncode\\mcode\\sday02\\src\\spring.xml");  
//ApplicationContext ac3=new FileSystemXmlApplicationContext("file:E:/eclipse/springMVC2/test/applicationContext.xml");// 两种文件路径形式“/”与“\\”的区别
    //从类路径  
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml");  
      
    HelloService helloService =  context.getBean("helloServiceImpl", HelloServiceImpl.class);  
    helloService.sayHello();

3、在web应用中使用

3.1、使用XmlWebApplicationContext

XmlWebApplicationContext context = new XmlWebApplicationContext();   
//默认的路径/WEB-INF/applicationContext.xml  
//applicationContext.xml文件名称 可以任意起  
//重新设置路径  
//context.setConfigLocations(new String[] {"/WEB-INF/classes/applicationContext.xml"});   
//设置ServletContext上下下文为web应用程序的上下文  
context.setServletContext(getServletContext());  
//刷新  
context.refresh();  
//根据id名称获取  
HelloDao helloDao = context.getBean("helloDaoImpl", HelloDaoImpl.class);  
//执行helloDao对象的方法  
helloDao.sayHello();  


3.2、使用WebApplicationContextUtils工具类

//直接采用getWebApplicationContext(getServletContext()) 获取context对象  
WebApplicationContext  context=   
WebApplicationContextUtils.getWebApplicationContext(getServletContext());  
//context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());  
System.out.println(context);  
HelloDao helloDao = context.getBean("helloDaoImpl", HelloDaoImpl.class);  
helloDao.sayHello()

两者的区别是:

1、当采用getWebApplicationContext(getServletContext())获取context对象的时候,输出的context对象为null  所以在使用

context.getBean(“helloDaoImpl”, HelloDaoImpl.class);会出现空指针的异常

   2、当采用getRequiredWebApplicationContext(getServletContext());获取context对象的时候 会出现如下bug

java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/106273.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 微信怎么设置自动回复机器人_微信群助手机器人

    微信怎么设置自动回复机器人_微信群助手机器人“傻瓜式”微信自动回复机器人配置教程首先下载Python和Pip到官网上去下源文件Python官网下载,Pip下载地址这里建议Pip不要直接在这下,后面会有提到。我下的是Python2.7.8,Python3可能和这个版本有点小区别。官网下的Python是安装文件,Pip则是免安装的源文件(我是将Python直接装在C盘,我把Pip中放在Python27目录里面)。…

    2022年9月30日
    5
  • 小数转int类型_怎样对结构体进行大小端转换

    小数转int类型_怎样对结构体进行大小端转换int16大小端转换:staticinlineuint16_tbswap_16(uint16_tx){  return(x>>8)|(x}int32大小端转换:staticinlineuint32_tbswap_32(uint32_tx){  x=((x>8)&0x00FF00FF); 

    2022年8月15日
    5
  • git 拉取远程分支到本地及本地切换分支

    拉取远程分支到本地及本地切换分支涉及的操作内容1.远程代码拉取到本地-2.本地合并其它分支代码-3.本地代码提交到远程指定仓库-4.本地切换分支1.远程代码拉取到本地首先确定要切换分支,查看当前本地及远程所有分支gitbranch-a红色为远程分支,白色为本地分支“*”为本地当前分支下面我们来切换一下远程分并在本地创建远程分支gitcheckout-b本地分支名origin/远程分支名远程代码拉取到本地已完成下面确认一下时代码记录gitlog/

    2022年4月7日
    1.4K
  • 九章算法_九章算法(杭州)科技有限公司

    九章算法_九章算法(杭州)科技有限公司1BST迭代器注意点:1.实际就是中序遍历的非递归写法,迭代器就是要用Stack存储数据,不过把不同的模块功能进行了分割,而不是一次完成中序遍历;2.可以把添加到Stack单独抽取成一个函数

    2022年8月3日
    5
  • Unity Odin从入门到精通(二):创建编辑器窗口「建议收藏」

    Unity Odin从入门到精通(二):创建编辑器窗口「建议收藏」前言:为了更加快速和高效的组织项目数据,开发者可以使用Odin来快速创建自定义编辑器窗口,以帮助组织项目数据。这就是Odin可以真正帮助提升工作流程的地方。

    2022年7月21日
    16
  • java 雪崩效应,七、微服务架构中的“雪崩效应”

    java 雪崩效应,七、微服务架构中的“雪崩效应”1.雪崩效应在微服务架构中,我们将业务拆分成一个个的服务,服务与服务之间可以相互调用,但是由于网络原因或者自身的原因,服务并不能保证服务的100%可用,如果单个服务出现问题,调用这个服务就会出现网络延迟,此时若有大量的网络涌入,会形成任务堆积,最终导致服务瘫痪。其实,在单体服务中,高并发也会导致服务瘫痪。见下一章,Jmeter模拟微服务当中的高并发场景在分布式系统中,由于网络原因或自身的原因,服…

    2022年7月13日
    15

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号