在Spring框架中,.properties
文件通常用于存储配置信息,如数据库连接、服务地址、应用参数等。以下是配置和使用 Properties 文件的详细步骤:
1. 创建 Properties 文件
在项目的 src/main/resources
目录下创建一个 .properties
文件,例如 application.properties
。
# application.properties
app.name=MyApplication
app.version=1.0.0
database.url=jdbc:mysql://localhost:3306/mydb
database.username=root
database.password=secret
2. 使用 @ConfigurationProperties
注解
从 Spring Boot 1.0 开始,推荐使用 @ConfigurationProperties
注解来绑定属性值到配置类中。
@Component
@ConfigurationProperties(prefix="app")
public class AppConfig {
private String name;
private String version