介紹
Spring Profiles 提供了一套隔離應用配置的方式,不同的 profiles 提供不同組合的配置,在不同的環境中,應用在啟動時通過選擇激活某些特定的 profiles 來適應運行時環境,以達到在不同的環境可以使用相同的一套程序代碼。
環境
- JDK 8
- Maven 3
- IntelliJ IDEA 2016
- Spring Boot 1.5.2.RELEASE
@Profiles
你可以在任何 @Component(@Service,@Repository) 或 @Configuration 注解標注的類中使用 @Profiles 注解:
1
2
3
|
public interface PaymentService { String createPaymentQrcode(); } |
1
2
3
4
5
6
7
8
|
@Service @Profile ( "alipay" ) public class AlipayService implements PaymentService { @Override public String createPaymentQrcode() { return "支付寶支付二維碼" ; } } |
1
2
3
4
5
6
7
8
|
@Service @Profile ({ "default" , "wechatpay" }) public class WechatpayService implements PaymentService { @Override public String createPaymentQrcode() { return "微信支付二維碼" ; } } |
在 Spring Boot 中,默認的 profile 是 default,因此,PaymentService.createPaymentQrcode() ->
微信支付二維碼。
你可以通過 spring.profiles.active
來激活某個特定 profile:
1
|
java -jar -Dspring.profiles.active='alipay' xxx.jar |
PaymentService.createPaymentQrcode() ->
支付寶支付二維碼。
多環境配置
在Spring Boot 中,多環境配置文件可以使用 application-{profile}.{properties|yml} 的方式。
1
2
3
4
5
6
7
|
@Component @ConfigurationProperties ( "jdbc" ) public class JdbcProperties { private String username; private String password; // getters and setters } |
開發環境 application-dev.properties
配置:
1
2
|
jdbc.username=root jdbc.password=123654 |
生產環境 application-prod.properties
配置:
1
2
|
jdbc.username=produser jdbc.password=16888888 |
或:
開發環境 application-dev.yml
配置:
1
2
3
|
jdbc: username: root password: 123654 |
生產環境 application-prod.yml
配置:
1
2
3
|
jdbc: username: produser password: 16888888 |
或:
只使用 application.yml,并在此文件中通過 --- 分隔符創建多 profile 配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
app: version: 1.0.0 spring: profiles: active: "dev" --- spring: profiles: dev jdbc: username: root password: 123654 --- spring: profiles: prod jdbc: username: produser password: 16888888 |
命令行啟動:
1
|
java -jar -Dspring.profiles.active=prod xxxx.jar |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://fanlychie.github.io/post/spring-boot-profiles-usage.html?utm_source=tuicool&utm_medium=referral