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

一.新建一个Java Bean:

package springdemo;

public class HelloBean {
private String helloWorld;
public String getHelloWorld() {
return helloWorld;
}
public void setHelloWorld(String helloWorld) {
this.helloWorld = helloWorld;
}
}

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

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

三.读取配置文件:

1.利用ClassPathXmlApplicationContext:

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

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

public interface BeanFactory {
public Object getBean(String id);
} //实现类ClassPathXmlApplicationContext
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder; public class ClassPathXmlApplicationContext implements BeanFactory { private Map<String , Object> beans = new HashMap<String, Object>(); //(IOC:Inverse of Control/DI:Dependency Injection)
public ClassPathXmlApplicationContext() throws Exception {
SAXBuilder sb=new SAXBuilder(); Document doc=sb.build(this.getClass().getClassLoader().getResourceAsStream("beans.xml")); //构造文档对象
Element root=doc.getRootElement(); //获取根元素HD
List list=root.getChildren("bean");//取名字为disk的所有元素
for(int i=0;i<list.size();i++){
Element element=(Element)list.get(i);
String id=element.getAttributeValue("id");
String clazz=element.getAttributeValue("class");
Object o = Class.forName(clazz).newInstance();
System.out.println(id);
System.out.println(clazz);
beans.put(id, o); for(Element propertyElement : (List<Element>)element.getChildren("property")) {
String name = propertyElement.getAttributeValue("name"); //userDAO
String bean = propertyElement.getAttributeValue("bean"); //u
Object beanObject = beans.get(bean);//UserDAOImpl instance String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
System.out.println("method name = " + methodName); Method m = o.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]);
m.invoke(o, beanObject);
}
}
} public Object getBean(String id) {
return beans.get(id);
}
}

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

ApplicationContext context = new ClassPathXmlApplicationContext("bean_config.xml");
HelloBean helloBean = (HelloBean)context.getBean("helloBean"); BeanFactory factory= new ClassPathXmlApplicationContext("bean_config.xml");
HelloBean helloBean = (HelloBean)factory.getBean("helloBean");

  ClassPathXmlApplicationContext层级关系如下:

2.利用FileSystemResource读取

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

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

Spring读取properties配置文件

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

一.利用spring读取properties 文件

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

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

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

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

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

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

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

ip=192.168.0.1
port=8080

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

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

三.用接口类WebApplicationContext来取。

private WebApplicationContext wac;
wac =WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
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. python 简单的单例模式日志模块

    # -*- coding: utf-8 -*-import logging def singleton(cls): instance = {} def _singleton(*args, **kw): ...

  2. xgCalendar在ASP.NET中的使用

    1.将wdCalendar文件夹考入项目中 2.在页面中添加引用,见3中head标签中定义 3.配置xgCalendar,两段代码放在一起就是完整的页面 body> <div> &l ...

  3. Spark分析之DAGScheduler

    DAGScheduler概述:是一个面向Stage层面的调度器: 主要入参有: dagScheduler.runJob(rdd, cleanedFunc, partitions, callSite, ...

  4. 2.1_Scikit-learn数据集

    scikit-learn数据集 我们将介绍sklearn中的数据集类,模块包括用于加载数据集的实用程序,包括加载和获取流行参考数据集的方法.它还具有一些人工数据生成器. sklearn.dataset ...

  5. 0_Simple__simplePrintf

    在设备代码中使用函数 printf(),没有新的认识. ▶ 源代码 #include <stdio.h> #include <cuda_runtime.h> #include ...

  6. sqlserver查询---分配cpu等资源

    数据库资源按需分配 https://www.cnblogs.com/i6first/p/4138365.html https://blog.csdn.net/kk185800961/article/d ...

  7. leetcode54

    class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) ...

  8. 20.OGNL与ValueStack(VS)-普通方法访问

    转自:https://wenku.baidu.com/view/84fa86ae360cba1aa911da02.html 首先在User中增加一个成员方法,代码如下: public String g ...

  9. 安装新操作系统 Windows 路径设置 节省C盘空间

    1.QQ个人文件夹设置到D盘,D:\ProgramData\QQ 2.IE收藏夹设置到D盘,IE缓存设置到D盘 例如我想把收藏夹默认的保存路径改到D:\study下.关闭Internet Explor ...

  10. Activity服务类-6 ManagementService服务类

    一共含有17个方法 // 获取包含了Activiti数据库模式的{表名.行计数}项的映射.Map<String, Long> getTableCount();//获取诸如任务.执行之类的A ...