使用PropertyPlaceholderConfigurer读取属性文件
1.簡(jiǎn)介
通常,當(dāng)我們考慮將多個(gè)應(yīng)用程序部署到生產(chǎn)環(huán)境之前在其中部署服務(wù)器時(shí),可以在外部屬性文件中配置特定于環(huán)境的參數(shù) 。 它可能是數(shù)據(jù)庫詳細(xì)信息,對(duì)于測(cè)試服務(wù)器和生產(chǎn)服務(wù)器而言,這是不同的。 因此最好選擇將數(shù)據(jù)庫配置文件保存在外部屬性文件中。 同樣,我們可以選擇將LDAP服務(wù)器詳細(xì)信息保留在外部屬性文件中。 有了屬性文件,我們就不需要觸摸配置XML文件,在該配置文件中,屬性文件的值可以直接作為$ {name}來獲取 。
我們需要做的就是在每次部署時(shí)都相應(yīng)地更新屬性文件,甚至無需觸摸Spring配置上下文文件。
在本教程中,我們將看到如何利用PropertyPlaceholderConfigurer讀取外部屬性文件值并在Spring中從bean配置中訪問它們。
2.實(shí)施
對(duì)于一個(gè)簡(jiǎn)單的演示,讓我們?cè)谀硞€(gè)外部位置創(chuàng)建一個(gè)屬性文件user.properties ,其內(nèi)容如下:
name=ramesh設(shè)置好之后,確保我們具有以下內(nèi)容:
applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"><bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="location"><value>file:/E:\/user.properties</value></property></bean><bean id="helloWorld" class="com.jcombat.bean.HelloWorld"><property name="name" value="${name}" /></bean></beans>請(qǐng)注意上面片段中突出顯示的部分。
我們?cè)谙旅嬗兄黝?#xff0c;我們將嘗試運(yùn)行它。
MainApp.java
package com.jcombat.client;import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;import com.jcombat.bean.HelloWorld;public class MainApp {public static void main(String[] args) {ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");HelloWorld hellWorld = (HelloWorld) context.getBean("helloWorld");hellWorld.sayHello();((ConfigurableApplicationContext)context).close();} }3.運(yùn)行應(yīng)用程序
將上述內(nèi)容作為Java應(yīng)用程序運(yùn)行將顯示為:
4.下載源代碼
- 下載源代碼
翻譯自: https://www.javacodegeeks.com/2016/03/read-property-files-propertyplaceholderconfigurer.html
總結(jié)
以上是生活随笔為你收集整理的使用PropertyPlaceholderConfigurer读取属性文件的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 局域网电脑联机(局域网电脑联机游戏)
- 下一篇: 您的JAX-RS API并非天生就等于: