使用PropertyPlaceholderConfigurer读取属性文件

  • Post author:
  • Post category:其他

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