springBoot总结-多配置文件实现:Profile方式、yaml多文档快
warning:
这篇文章距离上次修改已过438天,其中的内容可能已经有所变动。
在Spring Boot中,可以使用多Profile方式来实现多配置文件的切换。这里提供两种方式:通过application.properties文件和application.yml文件。
- 通过application.properties文件实现多Profile
在application.properties文件中,通过spring.profiles.active属性来指定当前激活的配置文件。例如,你有两个配置文件,一个是application-dev.properties,另一个是application-prod.properties。你可以这样指定当前激活的配置文件:
# application-dev.properties
spring.datasource.url=jdbc:mysql://localhost:3306/dev
spring.datasource.username=devuser
spring.datasource.password=devpass
# application-prod.properties
spring.datasource.url=jdbc:mysql://localhost:3306/prod
spring.datasource.username=produser
spring.datasource.password=prodpass然后在主配置文件application.properties中指定激活的配置文件:
# application.properties
spring.profiles.active=dev你可以通过传递一个参数到JVM来切换配置,例如:
java -jar yourapp.jar --spring.profiles.active=prod- 通过application.yml文件实现多Profile
在application.yml文件中,通过spring.config.activate.on-profile属性来指定当前激活的配置。例如:
# application.yml
spring:
profiles:
active: dev
---
spring:
config:
activate:
on-profile: dev
server:
port: 8081
---
spring:
config:
activate:
on-profile: prod
server:
port: 8082在这个例子中,如果spring.profiles.active被设置为dev,那么第二个和第三个块将不会被加载,只有第一个块中的配置会被加载。如果spring.profiles.active被设置为prod,那么第一和第三个块将不会被加载,只有第二个块中的配置会被加载。
你可以通过传递一个参数到JVM来切换配置,例如:
java -jar yourapp.jar --spring.profiles.active=prod这两种方式都可以实现多配置文件的管理,你可以根据项目的具体需求来选择使用哪种方式。
评论已关闭