Spring框架讀取property屬性文件常用5種方法
1、方式一:通過(guò)spring框架 PropertyPlaceholderConfigurer 工具實(shí)現(xiàn)
<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>
<!-- 數(shù)據(jù)源配置 -->
<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客戶端接口實(shí)現(xiàn)->
<bean id="dalClient" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
2、方式二:簡(jiǎn)化配置
<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"/>
<!-- 數(shù)據(jù)源配置 -->
<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客戶端接口實(shí)現(xiàn)-->
<bean id="dalClient" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--備注:如果${} 這種寫(xiě)法無(wú)法讀取到,或者編譯出錯(cuò),則增加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.
]]>
翻譯后:指定是否應(yīng)忽略未能找到用于替換鍵的屬性值。默認(rèn)值為“false”,表示如果它無(wú)法解析密鑰,此占位符配置程序?qū)⒁l(fā)異常。設(shè)置為“true”以允許配置程序傳遞密鑰對(duì)于上下文中尚未訪問(wèn)相關(guān)密鑰的任何其他用戶。
2) 為簡(jiǎn)化 PropertyPlaceholderConfigurer 的使用,Spring提供了<context:property-placeholder location="classpath:jdbc.properties" />元素,啟用它后,開(kāi)發(fā)者便不用配置PropertyPlaceholderConfigurer對(duì)象了。
PropertyPlaceholderConfigurer內(nèi)置的功能非常豐富,如果它未找到${xxx}中定義的xxx鍵,它還會(huì)去JVM系統(tǒng)屬性(System.getProperty())和環(huán)境變量(System.getenv())中尋找。其通過(guò)啟用systemPropertiesMode和searchSystemEnvironment屬性,開(kāi)發(fā)者能夠控制這一行為。context:property-placeholder大大的方便了我們數(shù)據(jù)庫(kù)的配置。這樣就可以為spring配置的bean的屬性設(shè)置值了。
備注:spring容器中最多只能定義一個(gè) context:property-placeholder,否則會(huì)報(bào)錯(cuò):Could not resolve placeholder XXX,但如果想引入多個(gè)屬性文件怎么辦那,可以使用通配符:<context:property-placeholder location="classpath*:conf*.properties"/>
3、方式三:通過(guò)對(duì)spring PropertyPlaceholderConfigurer bean工廠后置處理器的實(shí)現(xiàn),在java程序中進(jìn)行屬性文件的讀取
<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客戶端接口實(shí)現(xiàn)-->
<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 是個(gè)bean工廠后置處理器的實(shí)現(xiàn),也就是 BeanFactoryPostProcessor 接口的一個(gè)實(shí)現(xiàn)。
在Spring中,使用PropertyPlaceholderConfigurer可以在XML配置文件中加入外部屬性文件,當(dāng)然也可以指定外部文件的編碼。PropertyPlaceholderConfigurer可以將上下文
(配置文 件)中的屬性值放在另一個(gè)單獨(dú)的標(biāo)準(zhǔn)java Properties文件中去。在XML文件中用${key}替換指定的properties文件中的值。這樣的話,只需要對(duì)properties文件進(jìn)
行修改,而不用對(duì)xml配置文件進(jìn)行修改。
引入外部文件后,就可以在xml中用${key}替換指定的properties文件中的值,通常項(xiàng)目中都會(huì)將jdbc的配置放在properties文件中。
在啟動(dòng)容器時(shí),初始化bean時(shí),${key}就會(huì)替換成properties文件中的值。
*/
//存取properties配置文件key-value結(jié)果
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、方式四:通過(guò)ClassPathResource類進(jìn)行屬性文件的讀取使用
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");// 會(huì)重新加載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、方式五:通過(guò)ContextClassLoader進(jìn)行屬性文件的讀取使用
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文件沒(méi)有找到異常", 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"));
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Spring如何使用PropertyPlaceholderConfigurer讀取文件
- Spring Boot中@ConditionalOnProperty的使用方法
- Spring @value和@PropertySource注解使用方法解析
- Spring Boot自定義配置屬性源(PropertySource)
- Spring中property-placeholder的使用與解析詳解
- Spring boot中PropertySource注解的使用方法詳解
- spring boot 注入 property的三種方式(推薦)
- 詳解Spring Boot 自定義PropertySourceLoader
- spring-core組件詳解——PropertyResolver屬性解決器
相關(guān)文章
基于Java代碼實(shí)現(xiàn)數(shù)字在數(shù)組中出現(xiàn)次數(shù)超過(guò)一半
這篇文章主要介紹了基于Java代碼實(shí)現(xiàn)數(shù)字在數(shù)組中出現(xiàn)次數(shù)超過(guò)一半的相關(guān)資料,需要的朋友可以參考下2016-02-02
java?實(shí)現(xiàn)獲取指定位置后的第一個(gè)數(shù)字
這篇文章主要介紹了java?實(shí)現(xiàn)獲取指定位置后的第一個(gè)數(shù)字,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
基于Jmeter生成測(cè)試報(bào)告過(guò)程圖解
這篇文章主要介紹了基于Jmeter生成測(cè)試報(bào)告過(guò)程圖解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
手把手教你寫(xiě)Maven的archetype項(xiàng)目腳手架
本文主要介紹了Maven的archetype項(xiàng)目腳手架,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08
一篇文章帶了解如何用SpringBoot在RequestBody中優(yōu)雅的使用枚舉參數(shù)
這篇文章主要介紹了SpringBoot中RequestBodyAdvice使用枚舉參數(shù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
Java線程并發(fā)中常見(jiàn)的鎖機(jī)制詳細(xì)介紹
越來(lái)越多的互聯(lián)網(wǎng)企業(yè)面臨著用戶量膨脹而帶來(lái)的并發(fā)安全問(wèn)題。接下來(lái)通過(guò)本文給大家介紹Java線程并發(fā)中常見(jiàn)的鎖機(jī)制,感興趣的朋友一起看看吧2016-05-05
SpringBoot整合Mysql和Redis的詳細(xì)過(guò)程
這篇文章主要介紹了SpringBoot整合Mysql和Redis的示例代碼,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-02-02
mybatis那些約定的配置你真的都了解嗎(經(jīng)驗(yàn)總結(jié))
mybatsi中Mapper和xml文件之間有很多約定俗稱的規(guī)則,比如名稱匹配,包掃描,別名等,這些規(guī)則是什么。如果想更加靈活,該如何配置呢?今天就給大家講一下如何配置mybatsi的xml文件2021-06-06
MyBatis?Plus?導(dǎo)入IdType失敗的解決
這篇文章主要介紹了MyBatis?Plus?導(dǎo)入IdType失敗的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12

