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 ,分别保存为两套启动配置方案,然后在编程界面,就可以看到下图所示
![]()
选中启动方案,点击右侧绿色箭头,就可以达到灵活应对不同开发环境的目的
本文详细介绍了SpringBoot项目中如何通过application.yml和application-{env}
1万+

被折叠的 条评论
为什么被折叠?



