Skip to content

Chạy nhiều môi trường với Spring Profile

1. Tạo file config

Spring Profiles có sẵn trong Framework rồi nên bạn không cần thêm bất kì thư viện nào khác. Để sử dụng, các bạn tạo file config tại thư mục resources trong project. Mặc định Spring sẽ nhận các file có tên như sau:

application.properties
application.yml
application-{profile-name}.yml // .properties

ví dụ mình có 2 môi trường là local và aws, thì mình sẽ tạo ra các file như thế này:

application.yml
application-local.yml
application-aws.yml
application-common.yml
  • application là file config chính khai báo các enviroment.
  • application-local chỉ sử dụng khi chạy chương trình ở local
  • application-aws chỉ sử dụng khi chạy ở AWS
  • application-common là những config dùng chung, môi trường nào cũng cần.

Bây giờ, mình sẽ khai báo trong từng file như sau (Xóa bớt nội dung từng tệp rùi cho ngắn gọn):

application.yml

#application.yml
---
spring.profiles: local
spring.profiles.include: common, local
---
spring.profiles: aws
spring.profiles.include: common, aws
---

application-aws.yml

spring:
  datasource:
    username: xxx
    password: xxx

application-local.yml

spring:
  datasource:
    username: root
    password:
    url: jdbc:mysql://localhost:3306/news?useSSL=false&characterEncoding=UTF-8

application-common.yml

spring:
  jpa:
    properties:

Tadaa, xong, mình giải thích chút. bạn để ý trong file application.yml mình có khai báo 2 môi trường là local và aws. Tại mỗi môi trường sẽ include (bao gồm) các file config như kia. Khi mình kích hoạt aws chẳng hạn, Spring sẽ load tất cả config có trong application-common.yml và application-aws.yml.

2. Kích hoạt config

Để sử dụng một Profiles bạn có các cách sau:

Sử dụng spring.profiles.active trong file application.properties hoặc application.yml

spring.profiles.active=aws

3: Sử dụng JVM System Parameter (nên dùng)

-Dspring.profiles.active=aws

4: Environment Variable (Unix) (nên dùng)

export SPRING_PROFILES_ACTIVE=aws

3. Cách sử dụng @Profile

Khi đã có Profile rồi, ngoài các biến toàn cục được thay đổi theo môi trường, bạn cũng có thể toàn quyền quyết định xem trong code rằng Bean hay Class nào sẽ được quyền chạy ở môi trường nào. Bằng cách sử dụng annotation @Profile

// Bean này Spring chỉ khởi tạo và quản lý khi môi trường là `local`
@Component
@Profile("local")
public class LocalDatasourceConfig {}
// Ngoài ra bạn có thể sử dụng toàn tử logic ở đây, ví dụ:
@Component
@Profile("!local")
public class LocalDatasourceConfig {}