使用PropertyPlaceholderConfigurer读取属性文件

1.简介

通常,当我们考虑将多个应用程序部署到生产环境之前在其中部署服务器时,我们可以在外部属性文件中配置特定环境的参数 。 它可能是数据库详细信息,对于测试服务器和生产服务器而言,这是不同的。 因此最好选择将数据库配置文件保存在外部属性文件中。 同样,我们可以选择将LDAP服务器详细信息保留在外部属性文件中。 有了属性文件,我们就不需要触摸配置XML文件,在该配置文件中,属性文件的值可以直接作为$ {name}来获取

我们需要做的就是在每次部署时都相应地更新属性文件,甚至无需触摸Spring配置上下文文件。

在本教程中,我们将看到如何利用PropertyPlaceholderConfigurer读取外部属性文件值并在Spring中从bean配置中访问它们。

2.实施

对于一个简单的演示,让我们在某个外部位置创建一个属性文件user.properties ,其内容如下:

name=ramesh

设置好之后,确保我们具有以下内容:

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>

请注意上面片段中突出显示的部分。

我们在下面有主类,我们将尝试运行它。

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.运行应用程序

将上述内容作为Java应用程序运行将显示为:

卡

4.下载源代码

翻译自: https://www.javacodegeeks.com/2016/03/read-property-files-propertyplaceholderconfigurer.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值