博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java中读取配置文件的方法
阅读量:6979 次
发布时间:2019-06-27

本文共 5245 字,大约阅读时间需要 17 分钟。

hot3.png

一、使用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内容如下:

         
       
            
100001           
123
           
李四
            
1000000.00
            
  

 

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文件内容如下:

threads.max=50threas.min=2  timout=15.52  interactive=true  color=red  speed=50  name=Default User  

二、使用java.util.Properties读取

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"));      }  }  

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

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();

2、使用上下文(Context)

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

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

 

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://my.oschina.net/u/2300159/blog/728039

你可能感兴趣的文章
70.打印所有Spring boot载入的bean【从零开始学Spring Boot】
查看>>
jvm compile
查看>>
linux内核SMP负载均衡浅析
查看>>
display的block、none、inline属性及解释
查看>>
新的Mac下如何配置开发者账号信息
查看>>
非阻塞socket的连接
查看>>
UITextField的代理方法
查看>>
无人驾驶相关数据集
查看>>
C 的大致运行原理。
查看>>
关于jsp和eclipse服务器端的相关配置和JS的区别
查看>>
JavaScript - 数据类型和变量
查看>>
TCP/IP:IP选项处理
查看>>
【网摘】检测 iframe 是否加载完成
查看>>
cocos2dx 3.x(动态改变精灵的背景图片)
查看>>
cocos2d-x JS 获取当前系统时间(解决屏幕双击点击事件)
查看>>
支付宝接入参考博客
查看>>
学习Spring中遇到关于BeanFactory及测试类的问题
查看>>
现实迷途 第七章 特殊客户
查看>>
找水王
查看>>
fgets()用法笔记
查看>>