全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

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

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,而不用再去指定配置文件的具体位置。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


# spring  # java读取配置  # 读取配置文件  # 读取配置  # Java Spring读取和存储详细操作  # Java Spring框架创建项目与Bean的存储与读取详解  # java springboot中如何读取配置文件的属性  # java(包括springboot)读取resources下文件方式实现  # Java(springboot) 读取txt文本内容代码实例  # Java之Spring简单的读取和存储对象  # 配置文件  # 实现了  # 是一个  # 就会  # 放在  # 找不到  # 两种  # 可以用  # 去找  # 再去  # 即是  # 抛出  # 大家多多  # 新建一个  # 服务器配置  # 构建一个  # 容器内  # 取名字  # 文档  # 目录下 


相关文章: Python文件管理规范_工程实践说明【指导】  西安制作网站公司有哪些,西安货运司机用的最多的app或者网站是什么?  如何高效配置香港服务器实现快速建站?  岳西云建站教程与模板下载_一站式快速建站系统操作指南  建站主机服务器选型指南与性能优化方案解析  如何快速完成中国万网建站详细流程?  网站制作的步骤包括,正确网址格式怎么写?  广州商城建站系统开发成本与周期如何控制?  网站制作与设计教程,如何制作一个企业网站,建设网站的基本步骤有哪些?  广州网站设计制作一条龙,广州巨网网络科技有限公司是干什么的?  做企业网站制作流程,企业网站制作基本流程有哪些?  宁波免费建站如何选择可靠模板与平台?  为什么Go需要go mod文件_Go go mod文件作用说明  临沂网站制作企业,临沂第三中学官方网站?  网站制作的方法有哪些,如何将自己制作的网站发布到网上?  网站图片在线制作软件,怎么在图片上做链接?  我的世界制作壁纸网站下载,手机怎么换我的世界壁纸?  如何在IIS中新建站点并配置端口与物理路径?  义乌企业网站制作公司,请问义乌比较好的批发小商品的网站是什么?  官网网站制作腾讯审核要多久,联想路由器newifi官网  制作表格网站有哪些,线上表格怎么弄?  如何在Ubuntu系统下快速搭建WordPress个人网站?  建站主机是什么?如何选择适合的建站主机?  潮流网站制作头像软件下载,适合母子的网名有哪些?  图片制作网站免费软件,有没有免费的网站或软件可以将图片批量转为A4大小的pdf?  ppt制作免费网站有哪些,ppt模板免费下载网站?  c# await 一个已经完成的Task会发生什么  如何处理“XML格式不正确”错误 常见XML well-formed问题解决方法  Bpmn 2.0的XML文件怎么画流程图  Android自定义listview布局实现上拉加载下拉刷新功能  独立制作一个网站多少钱,建立网站需要花多少钱?  如何配置支付宝与微信支付功能?  如何在阿里云香港服务器快速搭建网站?  头像制作网站在线观看,除了站酷,还有哪些比较好的设计网站?  jQuery 常见小例汇总  如何注册花生壳免费域名并搭建个人网站?  ,巨量百应是干嘛的?  企业网站制作公司网页,推荐几家专业的天津网站制作公司?  湖北网站制作公司有哪些,湖北清能集团官网?  定制建站流程解析:需求评估与SEO优化功能开发指南  深圳企业网站制作设计,在深圳如何网上全流程注册公司?  关于BootStrap modal 在IOS9中不能弹出的解决方法(IOS 9 bootstrap modal ios 9 noticework)  javascript中对象的定义、使用以及对象和原型链操作小结  建站之星CMS五站合一模板配置与SEO优化指南  手机钓鱼网站怎么制作视频,怎样拦截钓鱼网站。怎么办?  天津个人网站制作公司,天津网约车驾驶员从业资格证官网?  音响网站制作视频教程,隆霸音响官方网站?  如何在IIS中新建站点并解决端口绑定冲突?  婚礼视频制作网站,学习*后期制作的网站有哪些?  如何通过网站建站时间优化SEO与用户体验? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。