在配置文件里配置 Bean 时, 有时需要在 Bean 的配置里混入系统部署的细节信息(例如: 文件路径, 数据源配置信息等). 而这些部署细节实际上需要和 Bean 配置相分离
Spring 提供了一个 PropertyPlaceholderConfigurer 的 BeanFactory 后置处理器, 这个处理器允许用户将 Bean 配置的部分内容外移到属性文件中. 可以在 Bean 配置文件里使用形式为 ${var} 的变量, PropertyPlaceholderConfigurer 从属性文件里加载属性, 并使用这些属性来替换变量.
Spring 还允许在属性文件中使用 ${propName},以实现属性之间的相互引用。
注册 PropertyPlaceholderConfigurer
定义模型
package xyz.huning.spring4.properties;
public class Account {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "Account [username=" + username + ", password=" + password + "]";
}
}
添加Properties文件:account.properties
account.username=huning account.password=ninghu
配置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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 导入外部的资源文件 -->
<!-- Spring2.0配置方式 -->
<!--
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:account.properties"></property>
</bean>
-->
<!-- 导入外部的资源文件 -->
<!--
Spring 2.5 之后配置方式
1) <beans> 中添加 context Schema 定义
2) 在配置文件中加入如下配置:
-->
<context:property-placeholder location="classpath:account.properties"/>
<!--配置一个 bean-->
<bean id="account1" class="xyz.huning.spring4.properties.Account">
<property name="username" value="${account.username}"></property>
<property name="password" value="${account.password}"></property>
</bean>
</beans>
添加测试类
package xyz.huning.spring4.properties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("properties.xml");
Account account1 = context.getBean("account1", Account.class);
System.out.println(account1);
((ClassPathXmlApplicationContext)context).close();
}
}
本文详细介绍了如何在Spring框架中通过属性文件配置Bean的细节信息,包括使用PropertyPlaceholderConfigurer处理器将配置参数从代码中分离出来,并在属性文件中实现属性之间的相互引用。演示了从创建Account类到添加account.properties文件,再到配置XML文件,最后通过测试类验证配置效果的完整过程。

6060

被折叠的 条评论
为什么被折叠?



