Java中spring讀取配置文件的幾種方法示例

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

創(chuàng)新互聯(lián)公司是一家集網(wǎng)站建設(shè),平陽企業(yè)網(wǎng)站建設(shè),平陽品牌網(wǎng)站建設(shè),網(wǎng)站定制,平陽網(wǎng)站建設(shè)報價,網(wǎng)絡(luò)營銷,網(wǎng)絡(luò)優(yōu)化,平陽網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強企業(yè)競爭力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時我們時刻保持專業(yè)、時尚、前沿,時刻以成就客戶成長自我,堅持不斷學(xué)習、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實用型網(wǎng)站。

一.新建一個Java Bean:

package springdemo;

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

二.構(gòu)建一個配置文件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實現(xiàn)了接口ApplicationContext,ApplicationContext實現(xiàn)了BeanFactory。其通過jdom進行XML配置文件的讀取,并構(gòu)建實例化Bean,放入容器內(nèi)。

public interface BeanFactory {
  public Object getBean(String id);
}

//實現(xiàn)類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")); //構(gòu)造文檔對象
    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都實現(xiàn)了接口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層級關(guān)系如下:

Java中spring讀取配置文件的幾種方法示例

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配置文件

介紹兩種技術(shù):利用spring讀取properties 文件和利用java.util.Properties讀?。?/p>

一.利用spring讀取properties 文件

還利用上面的HelloBean.java文件,構(gòu)造如下bean_config.properties文件:

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

屬性文件中的"helloBean"名稱即是Bean的別名設(shè)定,.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讀取屬性文件

比如,我們構(gòu)造一個ip_config.properties來保存服務(wù)器ip地址和端口,如:

ip=192.168.0.1

port=8080

我們可以用如下程序來獲得服務(wù)器配置信息:

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中配置啟動后,該類會自動去找對應(yīng)的bean,而不用再去指定配置文件的具體位置。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

文章題目:Java中spring讀取配置文件的幾種方法示例
分享網(wǎng)址:http://muchs.cn/article48/ihijhp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設(shè)、App開發(fā)、網(wǎng)站內(nèi)鏈、域名注冊、關(guān)鍵詞優(yōu)化、面包屑導(dǎo)航

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作