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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 光栅化[通俗易懂]

    光栅化[通俗易懂]定义一个宽高比(AspectRatio);还有垂直可视角度verticalfield-of-view(fovY)。垂直可视角度即从相机原点到上顶中点和下底中点的连线的夹角,可视角度大可以类比

    2022年7月2日
    22
  • 网卡绑定模式bond0(多个网卡bond)

    在现在的网络中,带宽越来越高,线路的带宽可以达到1000m的带宽,但是想要达到整体性能达到1000m的带宽却很难,因为网络i/o限制着,无法整体达到这么高的带宽,甚至有时以前买的服务器网卡带宽不咋地,导致整个网络的带宽无法提升。但是linux的bond模块和ifenslave网卡聚合工具可以解决这一问题。利用bond模块连接内核实现双网卡通信,使用ifens…

    2022年4月10日
    160
  • VM15pro安装MacOS10.15.1系统(超详细,可用)[通俗易懂]

    VM15pro安装MacOS10.15.1系统(超详细,可用)[通俗易懂]前段时间去开发了款app需要用到打包,Android打包就不说了那个不涉及到环境,但是ipa打包就烦了,还要在mac的环境中去打包,但是作为一个底层程序员为了一个打包去买一个macpro就有点亏了,………

    2022年10月1日
    2
  • 〖Python语法进阶篇⑩〗- 正则表达式的字符匹配「建议收藏」

    〖Python语法进阶篇⑩〗- 正则表达式的字符匹配「建议收藏」在上一章节我们对正则表达式有了一个比较宏观的认识,并且知道了正则表达式的主要功能是通过匹配规则来获取或者验证字符串中的数据。要想成功的进行字符串的匹配需要使用到正则表达式模块,正则表达式匹配规则以及需要被匹配的字符串。在这三个条件中,模块与字符串都是准备好的,只有匹配规则异常的灵活,而今天这个章节就是认识一下正则表达式中的特殊字符,通过这些字符就可以针对我们想要的数据进行匹配。

    2022年7月14日
    22
  • 消息队列之事务消息,RocketMQ 和 Kafka 是如何做的?

    消息队列之事务消息,RocketMQ 和 Kafka 是如何做的?

    2020年11月20日
    209
  • 周末随笔「建议收藏」

    随便记录,聊以自慰这段时间的心思在工作上,也有一段时间没写一些东西了,内心有一些想法,搁置起来了。去年有段时间想着搞搞副业,说实话副业没赚到多少,几百上千的,还是自己能力不够。还是想办法先努力提高主业的收入,作为一个打工者,目前无非就是看哪里搬砖收益更好一点,能有更多点的成长而已。作为程序员,自己对技术的热情大多数只是停留在工作的使用上。这个技术工作中用了没有热情也是强制去了解去学习,要不就慢慢等着淘汰。单独靠热情驱动,还没发现自己真正对什么东西充满热情,有时候觉得可悲,无奈。工作对于目前的我来.

    2022年3月1日
    41

发表回复

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

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