在 Spring Boot 中,配置文件用于管理应用程序的属性和参数值。它允许我们根据不同环境配置应用程序的行为,而无需修改代码。
1. 配置文件的类型
Spring Boot 支持多种类型的配置文件,包括:
application.properties
:使用键值对的格式进行配置。application.yml
:使用 YAML 格式进行配置。application.xml
:使用 XML 格式进行配置。
2. 配置文件的位置
Spring Boot 默认会在以下位置查找配置文件:
- 在类路径下的
/config
目录 - 在类路径下的根目录
- 在
classpath:/config/
目录 - 在
classpath:/
目录
我们可以通过在 application.properties
文件中添加 spring.config.location
或 spring.config.name
属性来指定自定义的配置文件位置。
3. 配置文件的内容
3.1. application.properties
使用键值对的格式,例如:
# 服务器端口配置
server.port=8080
# 数据库连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=123456
3.2. application.yml
使用 YAML 格式,例如:
# 服务器端口配置
server:
port: 8080
# 数据库连接配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: 123456
3.3. application.xml
使用 XML 格式,例如:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 服务器端口配置 -->
<server>
<port>8080</port>
</server>
<!-- 数据库连接配置 -->
<spring>
<datasource>
<url>jdbc:mysql://localhost:3306/mydb</url>
<username>root</username>
<password>123456</password>
</datasource>
</spring>
</configuration>
4. 加载配置文件
Spring Boot 会自动加载默认的配置文件。如果需要使用自定义的配置文件,可以在主类的 @SpringBootApplication
注解上添加 @PropertySource
注解。
@SpringBootApplication
@PropertySource(value = "classpath:custom.properties")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
5. 使用配置文件中的属性
在 Spring Boot 应用程序中,我们可以使用 @Value
注解将配置文件中的属性值注入到变量中。
@RestController
public class MyController {
@Value("${server.port}")
private int serverPort;
@GetMapping("/port")
public String getPort() {
return "Server port: " + serverPort;
}
}
上述示例中,serverPort
变量会自动注入 server.port
属性值。
6. 总结
使用配置文件可以简化 Spring Boot 应用程序的配置过程,提高灵活性和可维护性。通过选择合适的配置文件类型,指定位置和编写内容,我们可以轻松管理和修改应用程序的属性和参数值。
本文来自极简博客,作者:幽灵船长酱,转载请注明原文链接:Spring Boot 中配置文件使用