java中读取配置文件的方法
转自: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文件
- <span style="font-family:Microsoft YaHei;font-size:12px;">package com.styspace;
- 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);
- }
- }
- </span>
需要注意的是config.getString(“Account.name”)中的参数是Account.name,这个参数是XPath格式的,而且不能包含xml中的根元素。
使用到的config.xml内容如下:
- <span style="font-family:Microsoft YaHei;font-size:12px;"><?xml version="1.0" encoding="gbk"?>
- <Accounts>
- <Account type="by0003">
- <code>100001</code>
- <pass>123</pass>
- <name>李四</name>
- <money>1000000.00</money>
- </Account>
- </Accounts></span>
2、读取properties文件
- <span style="font-family:Microsoft YaHei;font-size:12px;">package com.styspace;
- 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);
- }
- }
- </span>
使用到的config.properties文件内容如下:
- <span style="font-family:Microsoft YaHei;font-size:12px;">threads.max=50threas.min=2
- timout=15.52
- interactive=true
- color=red
- speed=50
- name=Default User</span>
二、使用java.util.Properties读取
- <span style="font-family:Microsoft YaHei;font-size:12px;">package com.styspace;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.Properties;
- public class PropertiesTest {
- public static void main(String[] args){
- PropertiesTest pt = new PropertiesTest();
- try {
- pt.getProperties();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- private void getProperties() throws IOException {
- InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("com/styspace/config.properties");
- System.out.println("begin!!!");
- Properties properties = new Properties();
- try{
- properties.load(inputStream);
- }catch (IOException ioE){
- ioE.printStackTrace();
- }finally{
- inputStream.close();
- }
- System.out.println("name:"+properties.getProperty("name"));
- }
- }
- </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
- <span style="font-family:Microsoft YaHei;font-size:12px;"> BeanFactory factory = null; //声明
- 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();</span>
2、使用上下文(Context)
上下文更加高级:提供文本信息解析工具,包括对国际化支持;提供载入文件资源的通用方法,如图片;可以向注册为监听器的bean发送事件。
在很少的情况下,使用BeanFactory。
- <span style="font-family:Microsoft YaHei;font-size:12px;"> //从文件系统
- ApplicationContext context = new FileSystemXmlApplicationContext("file:D:\\Ncode\\mcode\\sday02\\src\\spring.xml");
- //从类路径
- ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml");
- HelloService helloService = context.getBean("helloServiceImpl", HelloServiceImpl.class);
- helloService.sayHello();</span>
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
java中读取配置文件的方法的更多相关文章
- Java中读取配置文件中的内容,并将其赋值给静态变量的方法
应用场景 项目开发中某个功能需要抽取成方法写成一个工具类,提供给别人使用.写过工具类的人都知道,工具类中的方法一般都是静态方法,可以直接使用类名点方法名调用, 使用很方便,比如判断某个对象是否为空的方 ...
- java中读取配置文件ResourceBundle和Properties两种方式比较
今天在开发的时候,需要把一些信息放到配置文件中,方便后续的修改,注意到用的是ResourceBundle读取配置文件的方式,记得之前也见过使用Properties的方式,就比较好奇这两种方式的区别,网 ...
- 在java中读取配置文件信息
public class PropertyUtil { public static final Properties PROP = new Properties(); /** * 读取配置文件的内容( ...
- java中读取配置文件
若是Javaweb项目,项目运行于tomcat或其他容器时,可以使用下面方式来获取文件的输入流 1.当属性文件放在src下面时 InputStream is = Thread.currentThrea ...
- JAVA中读取xls数据方法介绍
用例编号(UI-0001) 用例名称({验证页面跳转|验证元素文本}-简要明确表述) 验证类型 是否执行 初始URL 初始元素xpath 目标元素xpath 目标元素属性 期望结果 UI-0001 验 ...
- java中读取配置文件中的数据
1.先在项目中创建一个包(如:config),再创建一个配置文件(如:a.properties),添加配置信息如下:比如:name=kakaage=28 2.代码:import java.io.IOE ...
- java中读取配置文件内容,如读取.properties文件
http://blog.csdn.net/u012255097/article/details/53122760
- Java中读取.properties配置文件的通用类
由于Java中读取配置文件的代码比较固定,所以可以将读取配置文件的那部分功能单独作为一个类,以后可以复用.为了能够达到复用的目的,不能由配置文件中每一个属性生成一个函数去读取,我们需要一种通用的方法读 ...
- 面试突击75:SpringBoot 有几种读取配置文件的方法?
Spring Boot 中读取配置文件有以下 5 种方法: 使用 @Value 读取配置文件. 使用 @ConfigurationProperties 读取配置文件. 使用 Environment 读 ...
随机推荐
- mint-ui Picker的使用
<template> <div v-bind:style="{minHeight:clientHeight + 'px'}" id="recive-mi ...
- ip and port check 正则
在网页开发中可能会遇到需要对在页面输入的ip和端口进行正确性验证,那么正则表达式就是最有力的工具: 1:ip的正则表达式: 格式是由“.”分割的四部分,每部分的范围是0-255: 每段的正则可以分几部 ...
- windows环境下搭建RocketMQ
https://blog.csdn.net/hsl_1990_08_15/article/details/80077552 安装完rocketmq后,报磁盘空间不足,只需要修改启动脚本runbroke ...
- 异常点/离群点检测算法——LOF
http://blog.csdn.net/wangyibo0201/article/details/51705966 在数据挖掘方面,经常需要在做特征工程和模型训练之前对数据进行清洗,剔除无效数据和异 ...
- hdu5290树形dp
题意 给了n个点的数 每个点有一个w[i]权值,如果你选择了i这个点那么距离i这个点距离为w[i]的点将被除去,最后问 选则尽量少的点把这n个点全部删除 1<=n<=100000, 0&l ...
- PersistenceContext.properties()
在做 Spring + SpringMVC + SpringData 时,单元测试 报这个错误: java.lang.NoSuchMethodError:javax.persistence.Persi ...
- Shell 脚本编程基础
通过本文记录学习Linux Shell的一些笔记思考和总结,以加强记忆和理解.主要学习参考资料有: 1.<鸟哥的Linux私房菜-基础篇>第四版 2.菜鸟教程——Linux教程 3.ear ...
- Linux服务器---流量监控webalizer
webalize webzlizer是一个免费的web server分析工具,它能够分析apache.ftp等日志,将结果以html形式展示. 1.安装一些依赖软件 [root@localhost b ...
- RBAC
什么是rbac? -- 基于角色的权限控制 Role-Based Access Control 一个url就代表一个权限 // url分配给角色,角色分配给用户 -- 6个model,4张表 菜单表 ...
- [转载]Oracle中的NVL函数
Oracle中函数以前介绍的字符串处理,日期函数,数学函数,以及转换函数等等,还有一类函数是通用函数.主要有:NVL,NVL2,NULLIF,COALESCE,这几个函数用在各个类型上都可以. 下面简 ...