前言
Spring提供了读取外部properties文件的机制,可以使用读取到的数据为bean的属性赋值
实现步骤
-
准备外部properties文件
-
开启context命名空间的支持
Spring配置文件的头部配置要添加以下配置:
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
-
加载指定的properties文件
<context:property-placeholder location="classpath:db.properties"/>
-
使用获取到的数据
<property name="username" value="${user}"/>
-
注意
- 如果要加载所有的properties文件,使用
*.properties
表示加载所有后缀名为properties
的文件。 - 读取数据使用
${propertiesName}
,其中propertiesName
指properties文件中的属性名。
- 如果要加载所有的properties文件,使用
使用实例
-
PropertiesDemo.java
public class PropertiesDemo { private String username; private String password; public void setUsername(String username) { this.username = username; } public