1

spring | spring boot 多环境

 1 year ago
source link: https://benpaodewoniu.github.io/2022/11/07/spring12/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

这里利用 spring web 来说明多环境配置。

安装 spring web

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

Spring Boot 对多环境整合已经有了很好的支持,能够在打包,运行间自由切换环境。

创建不同环境的配置文件

既然每个环境的配置都不相同,索性将不同环境的配置放在不同的配置文件中,因此需要创建三个不同的配置文件,分别是

  • application-dev.properties
  • application-test.properties
  • application-prod.properties

「注意」:配置文件的名称一定要是application-name.properties或者application-name.yml格式。这个name可以自定义,主要用于区分。

此时整个项目中就有四个配置文件,加上application.properties

指定运行的环境

虽然你创建了各个环境的配置文件,但是 Spring Boot仍然不知道你要运行哪个环境,有以下两种方式指定:

配置文件中指定

application.properties 或者 application.yml 文件中指定,内容如下:

指定运行环境为测试环境
spring.profiles.active=test

application-test.propertiesserver.port = 8081
application-prod.propertiesserver.port = 8082

同样换成 yaml 也是如此,另外,yaml 可以把不同的环境都放到同一个文件中,使用 --- 做分隔。如下,只是 application.yml 的内容

spring:
profiles:
active: dev

---
server:
port: 8081
spring:
profiles: dev

---
server:
port: 8082
spring:
profiles: prod

以上配置有什么作用呢?

如果没有指定运行的环境,Spring Boot 默认会加载application.properties文件,而这个的文件又告诉Spring Boot 去找test环境的配置文件。

运行 jar 的时候指定

Spring Boot 内置的环境切换能够在运行Jar包的时候指定环境,命令如下:

java -jar xxx.jar --spring.profiles.active=test

以上命令指定了运行的环境是test


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK