Spring PropertyPlaceholderConfigurer Usage

本文介绍如何使用Spring框架中的PropertyPlaceholderConfigurer类实现属性文件的加载及变量替换功能。通过创建JavaBean、spring.xml配置文件和spring.properties文件,演示了如何在Spring配置文件中引用外部属性文件,并递归解析变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Spring里有一个PropertyPlaceholderConfigurer类,可以用来处理用一个properties文件里的内容来替换spring配置文件里使用${}的变量定义,比如有时候我们需要把对数控库的配置信息在别的properties文件里。

1. 首先创建一个Java Bean

package test; import org.apache.commons.lang.builder.ToStringBuilder; public class MyBean { private String name; private String prop1; private String prop2; private String prop3; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getProp1() { return prop1; } public void setProp1(String prop1) { this.prop1 = prop1; } public String getProp2() { return prop2; } public void setProp2(String prop2) { this.prop2 = prop2; } public String getProp3() { return prop3; } public void setProp3(String prop3) { this.prop3 = prop3; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }

2. 创建spring.xml文件

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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-2.0.xsd" default-lazy-init="true"> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath:test/spring.properties</value> </property> <property name="systemPropertiesMode"> <value>1</value> </property> <property name="searchSystemEnvironment"> <value>true</value> </property> <property name="ignoreUnresolvablePlaceholders"> <value>true</value> </property> </bean> <bean id="myBean" class="test.MyBean"> <property name="name"><value>${name}</value></property> <property name="prop1"><value>${prop1}</value></property> <property name="prop2"><value>${prop2}</value></property> <property name="prop3"><value>${prop3}</value></property> </bean> </beans>

配置文件中使用${name},${propx}来说明需要使用properties文件中的内容替换

3. 创建spring.properties文件,这里变量可以递归引用当前properties文件中定义的别的变量

name=kongxx prop1=111 prop2=${prop1}222 prop3=${prop2}333

4. 写一个测试程序

package test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext( "/test/spring.xml"); MyBean myBean = (MyBean) ctx.getBean("myBean"); System.out.println(myBean); } }

运行测试程序,输出如下:

test.MyBean@1649b44[name=kongxx,prop1=111,prop2=111222,prop3=111222333]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值