Springboot 項目,默認配置文件 application.yml 或 application.properties ,以該文件作爲主配置文件,將公共配置項,都集中在該文件,其餘根據環境不同,可分成多個yml文件或properties文件,
命名格式如:application-{env}.yml 或 application-{env}.properties
上述命名格式是一種規範,Springboot能夠自動識別,下面進行實際演練
application.yml
spring:
application:
name: demo
profiles:
active: @profileActive@ # 此處十分重要
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
datasource:
type: com.alibaba.druid.pool.DruidDataSource
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: true
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
server:
port: 8181
context-path: /demo
logging:
level: info
config: classpath:logback.xml
application-dev.yml 測試環境
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/db_demo?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false
username: root
password: 123456
redis:
host: 127.0.0.1
port: 6379
password: 123456
database: 15
pool:
max-active: 200
max-idle: 10
min-idle: 0
timeout: 3000
application-prod 正式環境
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://10.87.22.76:3306/db_demo?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false
username: root
password: 216379
redis:
host: 10.87.22.76
port: 6379
password: 216379
database: 15
pool:
max-active: 200
max-idle: 10
min-idle: 0
timeout: 3000
上面創建好了三個配置文件,分別對應
公共配置 application.yml
測試環境 application-dev.yml
正式環境 application-prod.yml
針對pom.xml的修改
<dependencies>
<!-- 此處省略依賴 -->
</dependencies>
<profiles>
<profile>
<id>prod</id>
<properties>
<profileActive>prod</profileActive>
</properties>
</profile>
<profile>
<id>dev</id>
<properties>
<profileActive>dev</profileActive>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
</profiles>
<build>
<finalName>demo</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>application-${profileActive}.yml</include>
<include>application.yml</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
項目配置至此宣告完成,下面是關於 啓動打包命令的描述
Maven 打包 指定profile文件
打包 測試環境
mvn clean package -P dev
打包正式環境
mvn clean package -P prod
Idea 開發工具 直接運行
在Springboot 啓動配置界面中,找到紅箭頭標註的地方,填寫dev 或者 prod ,分別保存爲兩套啓動配置方案,然後在編程界面,就可以看到下圖所示
選中啓動方案,點擊右側綠色箭頭,就可以達到靈活應對不同開發環境的目的