【框架篇】Spring Boot 配置文件(详细教程)
Spring Boot 配置文件是用来定义Spring Boot应用的行为的,它可以是application.properties
或application.yml
。
1. 使用application.properties
# 设置服务器端口
server.port=8080
# 设置应用的上下文路径
server.servlet.context-path=/myapp
# 设置数据库连接信息
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=myuser
spring.datasource.password=mypass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
2. 使用application.yml
server:
port: 8080
servlet:
context-path: /myapp
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: myuser
password: mypass
driver-class-name: com.mysql.jdbc.Driver
在Spring Boot中,配置文件的位置和名称是固定的,它们应该位于src/main/resources
目录下,并且分别命名为application.properties
或application.yml
。
3. 多环境配置
在application.properties
中使用spring.profiles
指定环境:
# 使用application-dev.properties作为开发环境的配置
spring.profiles.active=dev
或者在application.yml
中使用:
spring:
profiles:
active: dev
对于不同的环境,可以创建具有特定后缀的配置文件,例如:
application-dev.properties
application-test.properties
application-prod.properties
4. 动态配置
Spring Boot 支持从外部源(如环境变量、命令行参数等)动态加载配置。
例如,通过命令行设置属性:
java -jar myapp.jar --server.port=8081
或者使用环境变量:
export SERVER_PORT=8081
java -jar myapp.jar
5. 配置数据库
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=myuser
spring.datasource.password=mypass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
或者使用YAML格式:
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: myuser
password: mypass
driver-class-name: com.mysql.jdbc.Driver
6. 配置JPA
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
或者使用YAML格式:
spring:
jpa:
hibernate:
ddl-auto: update
show-sql: true
以上是Spring Boot配置文件的基本使用方法,包括使用.properties
文件和.yml
文件,设置多环境配置,以及配置数据库和JPA。
评论已关闭