当前位置: 移动技术网 > IT编程>开发语言>Java > Java中spring读取配置文件的几种方法示例

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

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

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网