1. 程式人生 > 程式設計 >Spring框架讀取property屬性檔案常用5種方法

Spring框架讀取property屬性檔案常用5種方法

1、方式一:通過spring框架 PropertyPlaceholderConfigurer 工具實現

<bean id="propertyConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="ignoreUnresolvablePlaceholders" value="true"/>
    <property name="locations">
      <value>classpath:conf/jdbc.properties</value>
    </property>
    <property name="fileEncoding">
      <value>UTF-8</value>
    </property>
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
  </bean>
  
  <!-- 資料來源配置 -->
  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
     destroy-method="close">
    <property name="driverClassName" value="${database.connection.driver}"/>
    <property name="url" value="${database.connection.url}"/>
    <property name="username" value="${database.connection.username}"/>
    <property name="password" value="${database.connection.password}"/>
  </bean>
  <!-- DAL客戶端介面實現->
  <bean id="dalClient" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"/>
  </bean>

2、方式二:簡化配置

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
  http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
  ">
  <context:property-placeholder location="classpath:conf/jdbc.properties" ignore-unresolvable="true"/>
  <!-- 資料來源配置 -->
  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
     destroy-method="close">
    <property name="driverClassName" value="${database.connection.driver}"/>
    <property name="url" value="${database.connection.url}"/>
    <property name="username" value="${database.connection.username}"/>
    <property name="password" value="${database.connection.password}"/>
  </bean>
  <!-- DAL客戶端介面實現-->
  <bean id="dalClient" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"/>
  </bean>
  <!--備註:如果${} 這種寫法無法讀取到,或者編譯出錯,則增加ignore-unresolvable="true"的屬性資訊,並新增上文的 名稱空間資訊-->
  
  jdbc.properties檔案:
  database.connection.driver=com.mysql.jdbc.Driver
  database.connection.url=jdbc:mysql://*.*.*.*:3306/mysql?characterEncoding=utf-8
  database.connection.username=*
  database.connection.password=*

上述配置理解:

1)ignore-unresolvable屬性的示意:

<xsd:documentation><![CDATA[
Specifies if failure to find the property value to replace a key should be ignored.
Default is "false",meaning that this placeholder configurer will raise an exception
if it cannot resolve a key. Set to "true" to allow the configurer to pass on the key

to any others in the context that have not yet visited the key in question.
]]>

翻譯後:指定是否應忽略未能找到用於替換鍵的屬性值。預設值為“false”,表示如果它無法解析金鑰,此佔位符配置程式將引發異常。設定為“true”以允許配置程式傳遞金鑰對於上下文中尚未訪問相關金鑰的任何其他使用者。

2) 為簡化 PropertyPlaceholderConfigurer 的使用,Spring提供了<context:property-placeholder location="classpath:jdbc.properties" />元素,啟用它後,開發者便不用配置PropertyPlaceholderConfigurer物件了。

PropertyPlaceholderConfigurer內建的功能非常豐富,如果它未找到${xxx}中定義的xxx鍵,它還會去JVM系統屬性(System.getProperty())和環境變數(System.getenv())中尋找。其通過啟用systemPropertiesMode和searchSystemEnvironment屬性,開發者能夠控制這一行為。context:property-placeholder大大的方便了我們資料庫的配置。這樣就可以為spring配置的bean的屬性設定值了。

備註:spring容器中最多隻能定義一個 context:property-placeholder,否則會報錯:Could not resolve placeholder XXX,但如果想引入多個屬性檔案怎麼辦那,可以使用萬用字元:<context:property-placeholder location="classpath*:conf*.properties"/>

3、方式三:通過對spring PropertyPlaceholderConfigurer bean工廠後置處理器的實現,在java程式中進行屬性檔案的讀取

<bean id="propertyConfigurer" class="com.weblearn.utils.PropertyConfigurer">
    <property name="locations">
      <list>
        <value>classpath:conf/web-sys-relation.properties</value>
        <value>classpath:conf/jdbc.properties</value>
        <value>classpath:conf/main-setting-web.properties</value>
      </list>
    </property>
    <property name="fileEncoding" value="UTF-8"/>
  </bean>
  <!-- DAL客戶端介面實現-->
  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
     destroy-method="close">
    <property name="driverClassName" value="${database.connection.driver}"/>
    <property name="url" value="${database.connection.url}"/>
    <property name="username" value="${database.connection.username}"/>
    <property name="password" value="${database.connection.password}"/>
  </bean>
  
  <bean id="dalClient" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"/>
  </bean>
public class PropertyConfigurer extends PropertyPlaceholderConfigurer {
    /* 
      PropertyPlaceholderConfigurer 是個bean工廠後置處理器的實現,也就是 BeanFactoryPostProcessor 介面的一個實現。
      在Spring中,使用PropertyPlaceholderConfigurer可以在XML配置檔案中加入外部屬性檔案,當然也可以指定外部檔案的編碼。PropertyPlaceholderConfigurer可以將上下文
    (配置文 件)中的屬性值放在另一個單獨的標準java Properties檔案中去。在XML檔案中用${key}替換指定的properties檔案中的值。這樣的話,只需要對properties檔案進
    行修改,而不用對xml配置檔案進行修改。
      引入外部檔案後,就可以在xml中用${key}替換指定的properties檔案中的值,通常專案中都會將jdbc的配置放在properties檔案中。
      在啟動容器時,初始化bean時,${key}就會替換成properties檔案中的值。
    */

    //存取properties配置檔案key-value結果
    private Properties props;

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess,Properties props)
        throws BeansException {
      super.processProperties(beanFactoryToProcess,props);
      this.props = props;
    }

    public String getProperty(String key) {
      return this.props.getProperty(key);
    }

    public String getProperty(String key,String defaultValue) {
      return this.props.getProperty(key,defaultValue);
    }

    public Object setProperty(String key,String value) {
      return this.props.setProperty(key,value);
    }

  }

  @Controller
  @RequestMapping("/")
  public class TestController {
    @Autowired
    PropertyConfigurer propertyConfigurer;

    @RequestMapping("/index.do")
    public String getIndex(HttpServletRequest request,HttpServletResponse response,Model model) {
      Map map = new HashMap<String,Object>();
      map.put("orderNo","111");

      String address1 = propertyConfigurer.getProperty("static.picture.address1");
      String resRoot = propertyConfigurer.getProperty("resRoot");
      String envName = propertyConfigurer.getProperty("database.connection.username");
      String keyzjbceshi = propertyConfigurer.getProperty("keyceshi");


      map.put("address1",address1);
      map.put("resRoot",resRoot);
      map.put("envName",envName);
      map.put("keyzjbceshi",keyzjbceshi);

      model.addAllAttributes(map);
      return "index/index.ftl";
    }
  }

4、方式四:通過ClassPathResource類進行屬性檔案的讀取使用

public class ReadPropertiesUtils1 {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReadPropertiesUtils1.class);

    private static Properties props = new Properties();

    static {
      ClassPathResource cpr = new ClassPathResource("conf/ref-system-relation.properties");// 會重新載入spring框架
      try {
        props.load(cpr.getInputStream());
      } catch (IOException exception) {
        LOGGER.error("ReadPropertiesUtils1 IOException",exception);
      }
    }

    private ReadPropertiesUtils1() {

    }

    public static String getValue(String key) {
      return (String) props.get(key);
    }

    public static void main(String[] args) {
      System.out.println("static.picture.address1>>>"+ ReadPropertiesUtils1.getValue("static.picture.address1"));
      System.out.println("static.picture.address2>>>"+ ReadPropertiesUtils1.getValue("static.picture.address2"));
    }

  }

5、方式五:通過ContextClassLoader進行屬性檔案的讀取使用

public class ReadPropertiesUtils2 {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReadPropertiesUtils2.class);

    public static String getValue(String key) {
      Properties properties = new Properties();
      try {
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("conf/ref-system-relation.properties");
        properties.load(inputStream);
      } catch (FileNotFoundException e) {
        LOGGER.error("conf/web-sys-relation.properties檔案沒有找到異常",e);
      } catch (IOException e) {
        LOGGER.error("IOException",e);
      }
      return properties.getProperty(key);
    }

    public static void main(String[] args) {
      System.out.println("static.picture.address1>>>" + ReadPropertiesUtils2.getValue("static.picture.address1"));
      System.out.println("static.picture.address2>>>" + ReadPropertiesUtils2.getValue("static.picture.address2"));
    }
  }

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。