一般我们在开发中,都有多套环境,比如数据库配置,有:开发、测试、发布三个环境。如果人工修改,一方面浪费人力,一方面也容易乱中出错。
Spring提供了profile的功能,可以配置多套配置,在运行时指定使用那套,这样代码只要一套,运行时加入不同参数就可以了。
如数据库配置application.yml
spring:
profiles: dev
datasource:
url: jdbc:mysql://localhost/db_dev?characterEncoding=utf-8
username: dev
password: 123456
jpa:
database: mysql
show-sql: true
hibernate:
ddl-auto: update
naming:
strategy: org.hibernate.cfg.ImprovedNamingStrategy
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5Dialect
---
spring:
profiles: release
datasource:
url: jdbc:mysql://localhost/db_release?characterEncoding=utf-8
username: release
password: 654321
jpa:
database: mysql
show-sql: true
hibernate:
ddl-auto: update
naming:
strategy: org.hibernate.cfg.ImprovedNamingStrategy
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5Dialect
比如在UnitTest中,加入:
@ActiveProfiles("dev")
即可使用dev的配置。
也可以在运行jar的时候加入
-Dspring.profiles.active=release参数来激活