Java中spring读取配置文件的几种方法示例

所属分类: 软件编程 / java 阅读数: 35
收藏 0 赞 0 分享

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的面向对象编程基本概念学习笔记整理

这篇文章主要介绍了Java的面向对象编程基本概念学习笔记整理,包括类与方法以及多态等支持面向对象语言中的重要特点,需要的朋友可以参考下
收藏 0 赞 0 分享

Eclipse下编写java程序突然不会自动生成R.java文件和包的解决办法

这篇文章主要介绍了Eclipse下编写java程序突然不会自动生成R.java文件和包的解决办法 的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

基于Java实现杨辉三角 LeetCode Pascal's Triangle

这篇文章主要介绍了基于Java实现杨辉三角 LeetCode Pascal's Triangle的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

Java中Spring获取bean方法小结

Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架,如何在程序中获取Spring配置的bean呢?下面通过本文给大家介绍Java中Spring获取bean方法小结,对spring获取bean方法相关知识感兴趣的朋友一起学习吧
收藏 0 赞 0 分享

如何计算Java对象占用了多少空间?

在Java中没有sizeof运算符,所以没办法知道一个对象到底占用了多大的空间,但是在分配对象的时候会有一些基本的规则,我们根据这些规则大致能判断出来对象大小,需要的朋友可以参考下
收藏 0 赞 0 分享

剖析Java中的事件处理与异常处理机制

这篇文章主要介绍了Java中的事件处理与异常处理机制,讲解Java是如何对事件或者异常作出响应以及定义异常的一些方法,需要的朋友可以参考下
收藏 0 赞 0 分享

详解Java的Struts2框架的结构及其数据转移方式

这篇文章主要介绍了详解Java的Struts2框架的结构及其数据转移方式,Struts框架是Java的SSH三大web开发框架之一,需要的朋友可以参考下
收藏 0 赞 0 分享

Java封装好的mail包发送电子邮件的类

本文给大家分享了2个java封装好的mail包发送电子邮件的类,并附上使用方法,小伙伴们可以根据自己的需求自由选择。
收藏 0 赞 0 分享

在Java的Struts中判断是否调用AJAX及用拦截器对其优化

这篇文章主要介绍了在Java的Struts中判断是否调用AJAX及用拦截器对其优化的方法,Struts框架是Java的SSH三大web开发框架之一,需要的朋友可以参考下
收藏 0 赞 0 分享

java多线程Future和Callable类示例分享

JAVA多线程实现方式主要有三种:继承Thread类、实现Runnable接口、使用ExecutorService、Callable、Future实现有返回结果的多线程。其中前两种方式线程执行完后都没有返回值,只有最后一种是带返回值的。今天我们就来研究下Future和Callab
收藏 0 赞 0 分享
查看更多