五種方式讓你在java中讀取properties文件內容不再是難題

2019獨角獸企業重金招聘Python工程師標準>>> hot3.png

方式1.通過context:property-placeholder加載配置文件jdbc.properties中的內容

<context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/>

  上面的配置和下面配置等價,是對下面配置的簡化

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="ignoreUnresolvablePlaceholders" value="true"/><property name="locations"><list><value>classpath:jdbc.properties</value></list></property>
</bean>

注意:這種方式下,如果你在spring-mvc.xml文件中有如下配置,則一定不能缺少下面的紅色部分,關于它的作用以及原理,參見另一篇博客:context:component-scan標簽的use-default-filters屬性的作用以及原理分析

<!-- 配置組件掃描,springmvc容器中只掃描Controller注解 -->
<context:component-scan base-package="com.hafiz.www" use-default-filters="false"><context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

方式2.使用注解的方式注入,主要用在java代碼中使用注解注入properties文件中相應的value值

<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean"><!-- 這里是PropertiesFactoryBean類,它也有個locations屬性,也是接收一個數組,跟上面一樣 --><property name="locations"><array><value>classpath:jdbc.properties</value></array></property>
</bean>

方式3.使用util:properties標簽進行暴露properties文件中的內容

<util:properties id="propertiesReader" location="classpath:jdbc.properties"/>

注意:使用上面這行配置,需要在spring-dao.xml文件的頭部聲明以下紅色的部分

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:util="http://www.springframework.org/schema/util"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://www.springframework.org/schema/util 
     http://www.springframework.org/schema/util/spring-util.xsd">

方式4.通過PropertyPlaceholderConfigurer在加載上下文的時候暴露properties到自定義子類的屬性中以供程序中使用

<bean id="propertyConfigurer" class="com.hafiz.www.util.PropertyConfigurer"><property name="ignoreUnresolvablePlaceholders" value="true"/><property name="ignoreResourceNotFound" value="true"/><property name="locations"><list><value>classpath:jdbc.properties</value></list></property>
</bean>

自定義類PropertyConfigurer的聲明如下:

package com.hafiz.www.util;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;import java.util.Properties;/*** Desc:properties配置文件讀取類* Created by hafiz.zhang on 2016/9/14.*/
public class PropertyConfigurer extends PropertyPlaceholderConfigurer {private Properties props;       // 存取properties配置文件key-value結果
@Overrideprotected 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);}
}

使用方式:在需要使用的類中使用@Autowired注解注入即可。

方式5.自定義工具類PropertyUtil,并在該類的static靜態代碼塊中讀取properties文件內容保存在static屬性中以供別的程序使用

package com.hafiz.www.util;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.*;
import java.util.Properties;/*** Desc:properties文件獲取工具類* Created by hafiz.zhang on 2016/9/15.*/
public class PropertyUtil {private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class);private static Properties props;static{loadProps();}synchronized static private void loadProps(){logger.info("開始加載properties文件內容.......");props = new Properties();InputStream in = null;try {<!--第一種,通過類加載器進行獲取properties文件流-->in = PropertyUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");<!--第二種,通過類進行獲取properties文件流-->//in = PropertyUtil.class.getResourceAsStream("/jdbc.properties");
            props.load(in);} catch (FileNotFoundException e) {logger.error("jdbc.properties文件未找到");} catch (IOException e) {logger.error("出現IOException");} finally {try {if(null != in) {in.close();}} catch (IOException e) {logger.error("jdbc.properties文件流關閉出現異常");}}logger.info("加載properties文件內容完成...........");logger.info("properties文件內容:" + props);}public static String getProperty(String key){if(null == props) {loadProps();}return props.getProperty(key);}public static String getProperty(String key, String defaultValue) {if(null == props) {loadProps();}return props.getProperty(key, defaultValue);}
}

說明:這樣的話,在該類被加載的時候,它就會自動讀取指定位置的配置文件內容并保存到靜態屬性中,高效且方便,一次加載,可多次使用。

四、注意事項及建議

  以上五種方式,前三種方式比較死板,而且如果你想在帶有@Controller注解的Bean中使用,你需要在SpringMVC的配置文件spring-mvc.xml中進行聲明,如果你想在帶有@Service、@Respository等非@Controller注解的Bean中進行使用,你需要在Spring的配置文件中spring.xml中進行聲明。原因請參見另一篇博客:Spring和SpringMVC父子容器關系初窺

  我個人比較建議第四種和第五種配置方式,第五種為最好,它連工具類對象都不需要注入,直接調用靜態方法進行獲取,而且只一次加載,效率也高。而且前三種方式都不是很靈活,需要修改@Value的鍵值。

五、測試驗證是否可用

1.首先我們創建PropertiesService

package com.hafiz.www.service;/*** Desc:java程序獲取properties文件內容的service* Created by hafiz.zhang on 2016/9/16.*/
public interface PropertiesService {/*** 第一種實現方式獲取properties文件中指定key的value** @return*/String getProperyByFirstWay();/*** 第二種實現方式獲取properties文件中指定key的value** @return*/String getProperyBySecondWay();/*** 第三種實現方式獲取properties文件中指定key的value** @return*/String getProperyByThirdWay();/*** 第四種實現方式獲取properties文件中指定key的value** @param key** @return*/String getProperyByFourthWay(String key);/*** 第四種實現方式獲取properties文件中指定key的value** @param key** @param defaultValue** @return*/String getProperyByFourthWay(String key, String defaultValue);/*** 第五種實現方式獲取properties文件中指定key的value** @param key** @return*/String getProperyByFifthWay(String key);/*** 第五種實現方式獲取properties文件中指定key的value** @param key** @param defaultValue** @return*/String getProperyByFifthWay(String key, String defaultValue);
}

2.創建實現類PropertiesServiceImpl

package com.hafiz.www.service.impl;import com.hafiz.www.service.PropertiesService;
import com.hafiz.www.util.PropertyConfigurer;
import com.hafiz.www.util.PropertyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;/*** Desc:java程序獲取properties文件內容的service的實現類* Created by hafiz.zhang on 2016/9/16.*/
@Service
public class PropertiesServiceImpl implements PropertiesService {@Value("${test}")private String testDataByFirst;@Value("#{prop.test}")private String testDataBySecond;@Value("#{propertiesReader[test]}")private String testDataByThird;@Autowiredprivate PropertyConfigurer pc;@Overridepublic String getProperyByFirstWay() {return testDataByFirst;}@Overridepublic String getProperyBySecondWay() {return testDataBySecond;}@Overridepublic String getProperyByThirdWay() {return testDataByThird;}@Overridepublic String getProperyByFourthWay(String key) {return pc.getProperty(key);}@Overridepublic String getProperyByFourthWay(String key, String defaultValue) {return pc.getProperty(key, defaultValue);}@Overridepublic String getProperyByFifthWay(String key) {return PropertyUtil.getPropery(key);}@Overridepublic String getProperyByFifthWay(String key, String defaultValue) {return PropertyUtil.getProperty(key, defaultValue);}
}

3.控制器類PropertyController

package com.hafiz.www.controller;import com.hafiz.www.service.PropertiesService;
import com.hafiz.www.util.PropertyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;/*** Desc:properties測試控制器* Created by hafiz.zhang on 2016/9/16.*/
@Controller
@RequestMapping("/prop")
public class PropertyController {@Autowiredprivate PropertiesService ps;@RequestMapping(value = "/way/first", method = RequestMethod.GET)@ResponseBodypublic String getPropertyByFirstWay(){return ps.getProperyByFirstWay();}@RequestMapping(value = "/way/second", method = RequestMethod.GET)@ResponseBodypublic String getPropertyBySecondWay(){return ps.getProperyBySecondWay();}@RequestMapping(value = "/way/third", method = RequestMethod.GET)@ResponseBodypublic String getPropertyByThirdWay(){return ps.getProperyByThirdWay();}@RequestMapping(value = "/way/fourth/{key}", method = RequestMethod.GET)@ResponseBodypublic String getPropertyByFourthWay(@PathVariable("key") String key){return ps.getProperyByFourthWay(key, "defaultValue");}@RequestMapping(value = "/way/fifth/{key}", method = RequestMethod.GET)@ResponseBodypublic String getPropertyByFifthWay(@PathVariable("key") String key){return PropertyUtil.getProperty(key, "defaultValue");}
}

4.jdbc.properties文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.1.196:3306/dev?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456
jdbc.maxActive=200
jdbc.minIdle=5
jdbc.initialSize=1
jdbc.maxWait=60000
jdbc.timeBetweenEvictionRunsMillis=60000
jdbc.minEvictableIdleTimeMillis=300000
jdbc.validationQuery=select 1 from t_user
jdbc.testWhileIdle=true
jdbc.testOnReturn=false
jdbc.poolPreparedStatements=true
jdbc.maxPoolPreparedStatementPerConnectionSize=20
jdbc.filters=stat
#test data
test=com.hafiz.www

5.項目結果圖

  

6.項目GitHub地址

  https://github.com/hafizzhang/SSM/branches?頁面下的propertiesConfigurer分支。

7.測試結果

  第一種方式

  

  第二種方式

  

  第三種方式

  

  第四種方式

  

  第五種方式

  

六、總結

  通過本次的梳理和測試,我們理解了Spring和SpringMVC的父子容器關系以及context:component-scan標簽包掃描時最容易忽略的use-default-filters屬性的作用以及原理。能夠更好地定位和快速解決再遇到的問題。總之,棒棒噠~~~

轉載于:https://my.oschina.net/zhangph89/blog/1579668

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/453667.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/453667.shtml
英文地址,請注明出處:http://en.pswp.cn/news/453667.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

hive metastore mysql_Hive MetaStore的結構

本篇主要是介紹Hive在MySQL中存儲的源數據的表結構。Hive MetaStore 數據庫表結構圖test.pngTBLS記錄數據表的信息字段解釋TBL_ID在hive中創建表的時候自動生成的一個id&#xff0c;用來表示&#xff0c;主鍵CREATE_TIME創建的數據表的時間&#xff0c;使用的是時間戳DBS_ID這個…

修煉一名程序員的職業水準

程序就是一系列按步驟進行的操作序列&#xff0c;它有好多種級別&#xff0c;比如最低級的微程序、次低級的匯編程序、高級的各種編程語言程序、最高級的腳本語言程序&#xff0c;也許我列的不對&#xff0c;但沒關系&#xff0c;我要說的是不管是那個級別的程序&#xff0c;其…

Rails開發細節《一》

常用命令 rails new new_app cd new_app rake db:create rails server rails generate controller Blog action1 action2 rails generate scaffold Product title:string description:textrails generate model Comment commenter:string body:text post:references rake db…

latex中怎樣使公式居中_LaTeX_多行公式對齊居中的同時選擇性的加編號

標簽: 【轉載請注明出處】http://www.cnblogs.com/mashiqi 2016/10/20 一年多沒寫博文了。今天寫一個短的,記錄一下使用LaTeX的一些經驗。 如何居中多行的公式呢?我試過很多種方法后,覺得下面這個最好用: 1 \begin{flalign*}2 % In this way (this arrange of &), the…

[SDOI2008]Cave 洞穴勘測

題目描述 輝輝熱衷于洞穴勘測。 某天&#xff0c;他按照地圖來到了一片被標記為JSZX的洞穴群地區。經過初步勘測&#xff0c;輝輝發現這片區域由n個洞穴&#xff08;分別編號為1到n&#xff09;以及若干通道組成&#xff0c;并且每條通道連接了恰好兩個洞穴。假如兩個洞穴可以通…

Linux指令大全

名稱&#xff1a;cat 使用權限&#xff1a;所有使用者 使用方式&#xff1a;cat [-AbeEnstTuv] [--help] [--version] fileName 說明&#xff1a;把檔案串連接后傳到基本輸出&#xff08;螢幕或加 > fileName 到另一個檔案&#xff09; 參數&#xff1a; -n 或 --number 由 …

mysql宏參數_C語言帶參數的宏定義

C語言允許宏帶有參數。在宏定義中的參數稱為“形式參數”&#xff0c;在宏調用中的參數稱為“實際參數”&#xff0c;這點和函數有些類似。對帶參數的宏&#xff0c;在展開過程中不僅要進行字符串替換&#xff0c;還要用實參去替換形參。帶參宏定義的一般形式為&#xff1a;#de…

自定義過濾器

首先在web.xml中對過濾器的監聽 1 <!-- 自定義過濾器 -->2 <filter>3 <filter-name>AscFilter</filter-name>4 <filter-class>com.llh.filter.AscFilter</filter-class>5 </filter>6 <filter-mapping>7 …

[MS Sql Server術語解釋]預讀,邏輯讀,物理讀

在MSSQL中使用 SET STATISTICS IO ON 打開IO統計功能之后&#xff0c;每次執行完一個查詢就會在下面的【消息】面板中顯示本次查詢IO的統計信息。 (0 行受影響) 表 demo。掃描計數 1&#xff0c;邏輯讀取 622 次&#xff0c;物理讀取 0 次&#xff0c;預讀 0 次&#xff0c;lob…

mysql 數據庫查詢測試_MySQL查詢測試經驗

測試表geoinfo,整個表超過1100萬行&#xff0c;表結構&#xff1a;CREATE TABLEgeoinfo (objectidint(11) NOT NULLAUTO_INCREMENT ,latitudedouble NOT NULL,longitudedouble NOT NULL,occupancybit(1) NOT NULL,timedatetime NOT NULL,cabidvarchar(16) NOT NULL,PRIMARY KEY…

更改阿里云域名解析臺里某個域名綁定的IP之后不能解析到新IP

1.由于要撤銷一組負載均衡&#xff0c;所以需要更改阿里云域名解析臺里某個域名由原來綁定的負載均衡公網IP換到服務器公網IP 2.在服務器上nginx指定了域名訪問&#xff0c;開啟nginx服務 3.暫時關閉該組負載均衡服務 4.實現通過服務器IP可以訪問項目&#xff0c;域名訪問不了 …

秒懂數據類型的真諦—Python基礎前傳(4)

一切編程語言都是人設計的&#xff0c;既然是人設計的&#xff0c;那么設計各種功能的時候就一定會有它的道理&#xff0c;那么設計數據類型的用意是什么呢&#xff1f; (一) 基本數據類型 基本數據類型&#xff1a; 數字 int字符串 str布爾值 bool列表 list元組 tuple字典 dic…

Linux 系統命令及其使用詳解(大全)

Linux 系統命令及其使用詳解(大全) (來源: 中國系統分析員) cat cd   chmod chown   cp cut   名稱&#xff1a;cat   使用權限&#xff1a;所有使用者   使用方式&#xff1a;cat[-AbeEnstTuv] [--help] [--version] fileName   說明&#xff1a;把檔案串連…

wordpress配置SMTP服務發送郵件

使用SMTP服務發送郵件&#xff0c;需要使用一個插件&#xff1a;http://wordpress.org/extend/plugins/wp-mail-smtp/ 下載完成以后解壓到plugin目錄&#xff0c;然后在插件中啟用這個插件。 配置SMTP服務 SMTP的選項 發送一封測試郵件吧 >>> 本文轉自齊師傅博客園博客…

使用rpm包安裝mysql_centos下利用rpm包安裝mysql

安裝mysql步驟&#xff1a;第一、 http://www.mysql.com/downloads/mysql-4.0.html下載MySQL-client-5.0.96-1.glibc23.x86_64.rpm和MySQL-server-5.0.96-1.glibc23.x86_64.rpm第二、安裝服務端&#xff1a;[rootlfl01 mysql]# rpm -ivh MySQL-server-5.1.73-1.glibc23.i386.rp…

maxN - 返回數組中N個最大元素 minN - 返回數組中N個最小元素

從提供的數組中返回 n 個最小元素。如果 n 大于或等于提供的數組長度&#xff0c;則返回原數組&#xff08;按降序排列&#xff09;。 結合使用Array.sort() 與展開操作符(...) &#xff0c;創建一個數組的淺克隆&#xff0c;并按降序排列。 使用 Array.slice() 以獲得指定的元…

Linux 常用命令

Linux之所以受到廣大計算機愛好者的喜愛&#xff0c;主要原因有兩個&#xff0c;首先它是自由軟件&#xff0c;用戶不用支付費用就可以使用它&#xff0c;并可根據自己的需要對它進行修改。另外&#xff0c;它具有Unix的全部功能&#xff0c;任何使用Unix系統或想要學習Unix系統…

使用Server 2008新GPO做驅動器映射

在Server 2003的時代&#xff0c;我們為用戶做網絡驅動器映射(以下就直接稱為Map Network Drive&#xff09;, 通常可能有以下的做法. 方法一: 做一個登錄腳本&#xff0c;放在DC的netlogon目錄&#xff0c;接著在“Active Directory用戶和計算機”控制臺的用戶屬性的Logon S…

electron 打包后 __static_electron開發客戶端注意事項(兼開源個人知識管理工具“想學嗎”)...

窗口間通信的問題electron窗口通信比nwjs要麻煩的多electron分主進程和渲染進程&#xff0c;渲染進程又分主窗口的渲染進程和子窗口的渲染進程主窗口的渲染進程給子窗口的渲染進程發消息subWin.webContents.on(dom-ready, () > {subWin.webContents.send(message, {title: s…

180118 有趣的人工智能對話小程序

print(Hello world!) #輸入 print(What is your name?) # ask for their name 詢問名字 myName input()   #該你來回答名字了 print(It is good to meet you, myName)  #根據你的名字來給你打個招呼 print(The length of your name is:)  #然后看下一句 print(len(…