转自: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文件

  1. <span style="font-family:Microsoft YaHei;font-size:12px;">package com.styspace;
  2. import org.apache.commons.configuration.Configuration;
  3. import org.apache.commons.configuration.ConfigurationException;
  4. import org.apache.commons.configuration.XMLConfiguration;
  5. public class xmlLoaderTest {
  6. public static void main(String[] args) throws ConfigurationException{
  7. Configuration config = new XMLConfiguration("com/styspace/config.xml");
  8. String name = config.getString("Account.name");
  9. System.out.println("name:" + name);
  10. }
  11. }
  12. </span>

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

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

  1. <span style="font-family:Microsoft YaHei;font-size:12px;"><?xml version="1.0" encoding="gbk"?>
  2. <Accounts>
  3. <Account type="by0003">
  4. <code>100001</code>
  5. <pass>123</pass>
  6. <name>李四</name>
  7. <money>1000000.00</money>
  8. </Account>
  9. </Accounts></span>

2、读取properties文件

  1. <span style="font-family:Microsoft YaHei;font-size:12px;">package com.styspace;
  2. import org.apache.commons.configuration.Configuration;
  3. import org.apache.commons.configuration.ConfigurationException;
  4. import org.apache.commons.configuration.PropertiesConfiguration;
  5. public class peropertiesLoaderTest {
  6. public static void main(String[] args) throws ConfigurationException{
  7. Configuration config = new PropertiesConfiguration("com/styspace/config.properties");
  8. String name = config.getString("name");
  9. System.out.println("name:" + name);
  10. }
  11. }
  12. </span>

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

  1. <span style="font-family:Microsoft YaHei;font-size:12px;">threads.max=50threas.min=2
  2. timout=15.52
  3. interactive=true
  4. color=red
  5. speed=50
  6. name=Default User</span>

二、使用java.util.Properties读取

  1. <span style="font-family:Microsoft YaHei;font-size:12px;">package com.styspace;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.util.Properties;
  5. public class PropertiesTest {
  6. public static void main(String[] args){
  7. PropertiesTest pt = new PropertiesTest();
  8. try {
  9. pt.getProperties();
  10. } catch (IOException e) {
  11. // TODO Auto-generated catch block
  12. e.printStackTrace();
  13. }
  14. }
  15. private void getProperties() throws IOException {
  16. InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("com/styspace/config.properties");
  17. System.out.println("begin!!!");
  18. Properties properties = new Properties();
  19. try{
  20. properties.load(inputStream);
  21. }catch (IOException ioE){
  22. ioE.printStackTrace();
  23. }finally{
  24. inputStream.close();
  25. }
  26. System.out.println("name:"+properties.getProperty("name"));
  27. }
  28. }
  29. </span>

需要注意的是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

  1. <span style="font-family:Microsoft YaHei;font-size:12px;">    BeanFactory factory = null; //声明
  2. ClassPathResource resource = new ClassPathResource("spring.xml");//类路径
  3. factory= new XmlBeanFactory(resource);
  4. FileSystemResource fileSystemResource = new FileSystemResource("D:\\Ncode\\mcode\\sday02\\src\\spring.xml");//文件路径
  5. factory= new XmlBeanFactory(fileSystemResource);
  6. //XmlBeanFactory(参数可以是resource或者fileSystemResource等
  7. //但是不能是 res 原因可以查看:文档Part III. Core Technologies 6. Resources
  8. //中6.2 The Resource interface 有关isOpen方法的说明);
  9. //InputStreamResource res = new InputStreamResource(new FileInputStream("D:\\Ncode\\mcode\\sday02\\src\\spring.xml"));//系统路径
  10. HelloService helloService = factory.getBean("helloServiceImpl", HelloServiceImpl.class);
  11. helloService.sayHello();</span>

2、使用上下文(Context)

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

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

  1. <span style="font-family:Microsoft YaHei;font-size:12px;">    //从文件系统
  2. ApplicationContext context = new FileSystemXmlApplicationContext("file:D:\\Ncode\\mcode\\sday02\\src\\spring.xml");
  3. //从类路径
  4. ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml");
  5. HelloService helloService =  context.getBean("helloServiceImpl", HelloServiceImpl.class);
  6. helloService.sayHello();</span>

3、在web应用中使用

3.1、使用XmlWebApplicationContext

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

3.2、使用WebApplicationContextUtils工具类

  1. //直接采用getWebApplicationContext(getServletContext()) 获取context对象
  2. WebApplicationContext  context=
  3. WebApplicationContextUtils.getWebApplicationContext(getServletContext());
  4. //context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
  5. System.out.println(context);
  6. HelloDao helloDao = context.getBean("helloDaoImpl", HelloDaoImpl.class);
  7. 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

java中读取配置文件的方法的更多相关文章

  1. Java中读取配置文件中的内容,并将其赋值给静态变量的方法

    应用场景 项目开发中某个功能需要抽取成方法写成一个工具类,提供给别人使用.写过工具类的人都知道,工具类中的方法一般都是静态方法,可以直接使用类名点方法名调用, 使用很方便,比如判断某个对象是否为空的方 ...

  2. java中读取配置文件ResourceBundle和Properties两种方式比较

    今天在开发的时候,需要把一些信息放到配置文件中,方便后续的修改,注意到用的是ResourceBundle读取配置文件的方式,记得之前也见过使用Properties的方式,就比较好奇这两种方式的区别,网 ...

  3. 在java中读取配置文件信息

    public class PropertyUtil { public static final Properties PROP = new Properties(); /** * 读取配置文件的内容( ...

  4. java中读取配置文件

    若是Javaweb项目,项目运行于tomcat或其他容器时,可以使用下面方式来获取文件的输入流 1.当属性文件放在src下面时 InputStream is = Thread.currentThrea ...

  5. JAVA中读取xls数据方法介绍

    用例编号(UI-0001) 用例名称({验证页面跳转|验证元素文本}-简要明确表述) 验证类型 是否执行 初始URL 初始元素xpath 目标元素xpath 目标元素属性 期望结果 UI-0001 验 ...

  6. java中读取配置文件中的数据

    1.先在项目中创建一个包(如:config),再创建一个配置文件(如:a.properties),添加配置信息如下:比如:name=kakaage=28 2.代码:import java.io.IOE ...

  7. java中读取配置文件内容,如读取.properties文件

    http://blog.csdn.net/u012255097/article/details/53122760

  8. Java中读取.properties配置文件的通用类

    由于Java中读取配置文件的代码比较固定,所以可以将读取配置文件的那部分功能单独作为一个类,以后可以复用.为了能够达到复用的目的,不能由配置文件中每一个属性生成一个函数去读取,我们需要一种通用的方法读 ...

  9. 面试突击75:SpringBoot 有几种读取配置文件的方法?

    Spring Boot 中读取配置文件有以下 5 种方法: 使用 @Value 读取配置文件. 使用 @ConfigurationProperties 读取配置文件. 使用 Environment 读 ...

随机推荐

  1. Jenkins. 安装过程中出现一个错误: No such plugin: cloudbees-folder

    安装过程中出现一个错误: No such plugin: cloudbees-folder 安装插件,有时候会报类似的错误:An error occurred during installation: ...

  2. js执行上下文

    js在执行是会有一个“准备工作”: 主要内容有 1.变量.函数表达式——>变量声明,默认赋值为undefined: 2.this——>赋值: 3.函数声明——>赋值: 这三种数据的准 ...

  3. C# SQLite 数据库操作

    C# SQLite 数据库操作学习 运行环境:Window7 64bit,.NetFramework4.61,C# 7.0 参考: SQLite 官网 SQL As Understood By SQL ...

  4. jQuery样式--css(name|pro|[,val|fn])

    css(name|pro|[,val|fn]) 概述 访问匹配元素的样式属性 参数 name  要访问的属性名称 name  一个或多个CSS属性组成的一个数组 properties  要设置为样式属 ...

  5. redis 缓存刷新

  6. Spring源码阅读(四)

    我们知道,在spring bean生命周期中,我们可以在不同阶段执行处理器或者方法,比如init-method,destroy方法,BeanPostProcessor接口等.那么这些处理器或方法的执行 ...

  7. XSS攻击原理、示例和防范措施

    XSS攻击 XSS(Cross-Site Scripting,跨站脚本)攻击历史悠久,是危害范围非常广的攻击方式. Cross-Site Stripting的缩写本应该是CSS,但是为了避免和Casc ...

  8. JavaScript:原生JS实现Facebook实时消息抓捕

    基础知识准备: HTML5给我们提供了一个新的对象叫作:MutationObserver.为了兼容,还有WebKitMutationObserver.MozMutationObserver,挂靠在wi ...

  9. mysql-day06

    ##视图 - 什么是视图:在数据库中存在多种对象,表和视图都是数据库中的对象,创建视图时名称不能和表重名,视图实际上就代表一段sql查询语句,也可以理解成视图是一张虚拟的表,此虚拟表中的数据会随着原表 ...

  10. [转载]Oracle数据库 sql%found,sql%notfound,sql%rowcount

    sql%found,sql%notfound,sql%rowcount 在执行DML(insert,update,delete)语句时,可以用到以下三个隐式游标(游标是维护查询结果的内存中的一个区域, ...