springboot基础篇—SpringBoot 配置
warning:
这篇文章距离上次修改已过432天,其中的内容可能已经有所变动。
在Spring Boot中,配置文件主要有两种形式:application.properties和application.yml。
application.properties示例:
# 服务器端口
server.port=8080
# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=myuser
spring.datasource.password=mypass
spring.datasource.driver-class-name=com.mysql.jdbc.Driverapplication.yml示例:
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: myuser
password: mypass
driver-class-name: com.mysql.jdbc.Driver在Spring Boot应用中,配置文件的位置和名称是固定的,必须放在类路径的/resources目录下,或者说是classpath:/、classpath:/config/等目录下,Spring Boot应用会自动加载它们。
配置文件的优先级:
- 命令行参数(例如:
java -jar app.jar --spring.profiles.active=prod) - 环境变量
- 从
java:comp/env得到的变量 - JVM参数
- 通过
RandomValuePropertySource生成的random.*属性 - 应用程序的
defaultProperties定义 - 应用程序配置文件(
application.properties) - 应用程序配置文件(
application.yml) - 在
@Test注解的测试中,@SpringBootTest的properties属性 - 命令行参数(例如:
java -jar app.jar --spring.config.location=file:/path/to/application.properties) - 由
SpringApplication.setDefaultProperties设置的默认属性
在实际开发中,可以通过@Value注解、Environment类或@ConfigurationProperties注解来使用配置文件中的属性。
评论已关闭