1. 程式人生 > >Spring boot中用Profile配置多個環境引數

Spring boot中用Profile配置多個環境引數

一般我們在開發中,都有多套環境,比如資料庫配置,有:開發、測試、釋出三個環境。如果人工修改,一方面浪費人力,一方面也容易亂中出錯。

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
引數來啟用