Spring读取配置XML文件分三步:

一.新建一个Java Bean:

  1. package springdemo;
  2.  
  3. public class HelloBean {
  4. private String helloWorld;
  5. public String getHelloWorld() {
  6. return helloWorld;
  7. }
  8. public void setHelloWorld(String helloWorld) {
  9. this.helloWorld = helloWorld;
  10. }
  11. }

二.构建一个配置文件bean_config.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd" >
  3. <beans>
  4.   <bean id="helloBean" class="springdemo.HelloBean">
  5.     <property name="helloWorld">
  6.       <value>Hello!chb!</value>
  7.     </property>
  8.   </bean>
  9. </beans>

三.读取配置文件:

1.利用ClassPathXmlApplicationContext:

  1. ApplicationContext context = new ClassPathXmlApplicationContext("bean_config.xml");
  2. //这种用法不够灵活,不建议使用。
  3. HelloBean helloBean = (HelloBean)context.getBean("helloBean");
  4. System.out.println(helloBean.getHelloWorld());

  ClassPathXmlApplicationContext实现了接口ApplicationContext,ApplicationContext实现了BeanFactory。其通过jdom进行XML配置文件的读取,并构建实例化Bean,放入容器内。

  1. public interface BeanFactory {
  2. public Object getBean(String id);
  3. }
  4.  
  5. //实现类ClassPathXmlApplicationContext
  6. import java.lang.reflect.Method;
  7. import java.util.HashMap;
  8. import java.util.List;
  9. import java.util.Map;
  10.  
  11. import org.jdom.Document;
  12. import org.jdom.Element;
  13. import org.jdom.input.SAXBuilder;
  14.  
  15. public class ClassPathXmlApplicationContext implements BeanFactory {
  16.  
  17. private Map<String , Object> beans = new HashMap<String, Object>();
  18.  
  19. //(IOC:Inverse of Control/DI:Dependency Injection)
  20. public ClassPathXmlApplicationContext() throws Exception {
  21. SAXBuilder sb=new SAXBuilder();
  22.  
  23. Document doc=sb.build(this.getClass().getClassLoader().getResourceAsStream("beans.xml")); //构造文档对象
  24. Element root=doc.getRootElement(); //获取根元素HD
  25. List list=root.getChildren("bean");//取名字为disk的所有元素
  26. for(int i=0;i<list.size();i++){
  27. Element element=(Element)list.get(i);
  28. String id=element.getAttributeValue("id");
  29. String clazz=element.getAttributeValue("class");
  30. Object o = Class.forName(clazz).newInstance();
  31. System.out.println(id);
  32. System.out.println(clazz);
  33. beans.put(id, o);
  34.  
  35. for(Element propertyElement : (List<Element>)element.getChildren("property")) {
  36. String name = propertyElement.getAttributeValue("name"); //userDAO
  37. String bean = propertyElement.getAttributeValue("bean"); //u
  38. Object beanObject = beans.get(bean);//UserDAOImpl instance
  39.  
  40. String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
  41. System.out.println("method name = " + methodName);
  42.  
  43. Method m = o.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]);
  44. m.invoke(o, beanObject);
  45. }
  46. }
  47. }
  48.  
  49. public Object getBean(String id) {
  50. return beans.get(id);
  51. }
  52. }

  BeanFactory是一个很根的接口,ApplicationContext和ClassPathXmlApplicationContext都实现了接口BeanFactory,所以也可以这么写:

  1. ApplicationContext context = new ClassPathXmlApplicationContext("bean_config.xml");
  2. HelloBean helloBean = (HelloBean)context.getBean("helloBean");
  3.  
  4. BeanFactory factory= new ClassPathXmlApplicationContext("bean_config.xml");
  5. HelloBean helloBean = (HelloBean)factory.getBean("helloBean");

  ClassPathXmlApplicationContext层级关系如下:

2.利用FileSystemResource读取

  1. Resource rs = new FileSystemResource("D:/software/tomcat/webapps/springWebDemo/WEB-INF/classes/bean_config.xml");
  2. BeanFactory factory = new XmlBeanFactory(rs);
  3. HelloBean helloBean = (HelloBean)factory.getBean("helloBean");
  4. System.out.println(helloBean.getHelloWorld());

注意:利用FileSystemResource,则配置文件必须放在project直接目录下,或者写明绝对路径,否则就会抛出找不到文件的异常。

Spring读取properties配置文件

介绍两种技术:利用spring读取properties 文件和利用java.util.Properties读取:

一.利用spring读取properties 文件

  还利用上面的HelloBean.java文件,构造如下bean_config.properties文件:

  1. helloBean.class=springdemo.HelloBean
  2. helloBean.helloWorld=Hello!HelloWorld!

  属性文件中的"helloBean"名称即是Bean的别名设定,.class用于指定类来源。

然后利用org.springframework.beans.factory.support.PropertiesBeanDefinitionReader来读取属性文件。

  1. BeanDefinitionRegistry reg = new DefaultListableBeanFactory();
  2. PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(reg);
  3. reader.loadBeanDefinitions(new ClassPathResource("bean_config.properties"));
  4. BeanFactory factory = (BeanFactory)reg;
  5. HelloBean helloBean = (HelloBean)factory.getBean("helloBean");
  6. System.out.println(helloBean.getHelloWorld());

二.利用java.util.Properties读取属性文件

  比如,我们构造一个ip_config.properties来保存服务器ip地址和端口,如:

  1. ip=192.168.0.1
  2. port=8080

  我们可以用如下程序来获得服务器配置信息:

  1. InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("ip_config.properties");
  2. Properties p = new Properties();
  3. try {
  4. p.load(inputStream);
  5. } catch (IOException e1) {
  6. e1.printStackTrace();
  7. }
  8. System.out.println("ip:"+p.getProperty("ip")+",port:"+p.getProperty("port"));

三.用接口类WebApplicationContext来取。

  1. private WebApplicationContext wac;
  2. wac =WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
  3. wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
  4. JdbcTemplate jdbcTemplate = (JdbcTemplate)ctx.getBean("jdbcTemplate");

  其中,jdbcTemplate为spring配置文件中的一个bean的id值。

  这种用法比较灵活,spring配置文件在web中配置启动后,该类会自动去找对应的bean,而不用再去指定配置文件的具体位置。

Java中spring读取配置文件的几种方法的更多相关文章

  1. java读取配置文件的几种方法

    java读取配置文件的几种方法 原文地址:http://hbcui1984.iteye.com/blog/56496         在现实工作中,我们常常需要保存一些系统配置信息,大家一般都会选择配 ...

  2. Java中获取键盘输入值的三种方法

    Java中获取键盘输入值的三种方法     Java程序开发过程中,需要从键盘获取输入值是常有的事,但Java它偏偏就没有像c语言给我们提供的scanf(),C++给我们提供的cin()获取键盘输入值 ...

  3. 转:java读取配置文件的几种方法

    转自: http://www.iteye.com/topic/56496 在现实工作中,我们常常需要保存一些系统配置信息,大家一般都会选择配置文件来完成,本文根据笔者工作中用到的读取配置文件的方法小小 ...

  4. Spring读取配置文件的几种方式

    import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; imp ...

  5. 关于spring读取配置文件的两种方式

    很多时候我们把需要随时调整的参数需要放在配置文件中单独进行读取,这就是软编码,相对于硬编码,软编码可以避免频繁修改类文件,频繁编译,必要时只需要用文本编辑器打开配置文件更改参数就行.但没有使用框架之前 ...

  6. Springboot读取配置文件的两种方法

    第一种: application.yml配置中的参数: zip: Hello Springboot 方法读取: @RestController public class ControllerTest ...

  7. SpringBoot 常用读取配置文件的 3 种方法!

    我们在SpringBoot框架进行项目开发中该如何优雅的读取配置呢?或者说对于一些List或者Map应该如何配置呢? 本篇主要解决如下几个问题: 1.Spring Boot有哪些常用的读取配置文件方式 ...

  8. Java中遍历Map集合的四种方法

    在Java中如何遍历Map对象 How to Iterate Over a Map in Java 在java中遍历Map有不少的方法.我们看一下最常用的方法及其优缺点. 既然java中的所有map都 ...

  9. java中调用dll文件的两种方法

    一中是用JNA方法,另外是用JNative方法,两种都是转载来的, JNA地址:http://blog.csdn.net/shendl/article/details/3589676   JNativ ...

随机推荐

  1. [UE4]事件处理(Handling Events)和委托(Delegate)代码示例(一)

    1. 通过重写虚函数来处理事件 MyTriggerVolume.h 自定义一个Actor类,添加一个 Box 组件作为触发区域,然后通过重写虚函数——NotifyActorBeginOverlap, ...

  2. Spark分析之Master

    override def preStart() { logInfo("Starting Spark master at " + masterUrl) webUi.bind() // ...

  3. 《Linux内核精髓:精通Linux内核必会的75个绝技》一HACK #19 ext4的调整

    HACK #19 ext4的调整 本节介绍可以从用户空间执行的ext4调整.ext4在sysfs中有一些关于调整的特殊文件(见表3-6).使用这些特殊文件,就不用进行内核编译.重启,直接从用户空间确认 ...

  4. MySQL数据库索引(中)

    上一篇回顾: 1.一个索引对应一颗B+树,所有的真实记录都是存在叶子节点里面的,所有的项目录都存在内节点或者说根节点上. 2.innodb会为我们的表格主键添加一个聚簇索引,如果没有主键的话数据库是会 ...

  5. mysql更新(七) MySQl创建用户和授权

    14-补充内容:MySQl创建用户和授权   权限管理 我们知道我们的最高权限管理者是root用户,它拥有着最高的权限操作.包括select.update.delete.update.grant等操作 ...

  6. IDEA设置syso快捷键输出System.out.println();

    用Eclipse时间长了, 就习惯之前的快捷键! 当然, IDEA不愧是Java开发的”利器”! 写起代码就是一个字 – “爽”! 建议大家可以去尝试一下! 当然, 在IDEA中输出System.ou ...

  7. python拓展3 常用算法

    知识内容: 1.递归复习 2.算法基础概念 3.查找与排序 参考资料: http://python3-cookbook.readthedocs.io/zh_CN/latest/index.html h ...

  8. [Flutter] 支持描边效果的Text

    新版的flutter已经自带这个功能了.TextSyle 中一个shadow . 目前flutter中没找到很好的办法给Text增加描边.自己扩展了一个TextEx,可以实现简单的描边效果,能满足大部 ...

  9. Java虚拟机汇编代码

    0:将一个常量加载到操作数栈 3:数值从操作数栈存储到局部变量表 4:将int类型的常量加载到操作数栈 5:数值从操作数栈存储到局部变量表 6:将一个局部变量加载到操作栈 7:将一个局部变量加载到操作 ...

  10. php缓存类

    <?php /* * 缓存类 cache * 实 例: include( "cache.php" ); $cache = new cache(30); $cache-> ...