介紹
Spring Profiles 提供了一套隔離應(yīng)用配置的方式,不同的 profiles 提供不同組合的配置,在不同的環(huán)境中,應(yīng)用在啟動時通過選擇激活某些特定的 profiles 來適應(yīng)運行時環(huán)境,以達到在不同的環(huán)境可以使用相同的一套程序代碼。
環(huán)境
- JDK 8
- Maven 3
- IntelliJ IDEA 2016
- Spring Boot 1.5.2.RELEASE
@Profiles
你可以在任何 @Component(@Service,@Repository) 或 @Configuration 注解標(biāo)注的類中使用 @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() ->
支付寶支付二維碼。
多環(huán)境配置
在Spring Boot 中,多環(huán)境配置文件可以使用 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 } |
開發(fā)環(huán)境 application-dev.properties
配置:
1
2
|
jdbc.username=root jdbc.password=123654 |
生產(chǎn)環(huán)境 application-prod.properties
配置:
1
2
|
jdbc.username=produser jdbc.password=16888888 |
或:
開發(fā)環(huán)境 application-dev.yml
配置:
1
2
3
|
jdbc: username: root password: 123654 |
生產(chǎn)環(huán)境 application-prod.yml
配置:
1
2
3
|
jdbc: username: produser password: 16888888 |
或:
只使用 application.yml,并在此文件中通過 --- 分隔符創(chuàng)建多 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 |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://fanlychie.github.io/post/spring-boot-profiles-usage.html?utm_source=tuicool&utm_medium=referral