软件编程
位置:首页>> 软件编程>> java编程>> 详解Spring Boot Profiles 配置和使用

详解Spring Boot Profiles 配置和使用

作者:fanlychie  发布时间:2021-10-05 22:54:57 

标签:Spring,Boot,Profile

介绍

Spring Profiles 提供了一套隔离应用配置的方式,不同的 profiles 提供不同组合的配置,在不同的环境中,应用在启动时通过选择激活某些特定的 profiles 来适应运行时环境,以达到在不同的环境可以使用相同的一套程序代码。

环境

  1. JDK 8

  2. Maven 3

  3. IntelliJ IDEA 2016

  4. Spring Boot 1.5.2.RELEASE

@Profiles

你可以在任何 @Component(@Service,@Repository) 或 @Configuration 注解标注的类中使用 @Profiles 注解:


public interface PaymentService {
 String createPaymentQrcode();
}

@Service
@Profile("alipay")
public class AlipayService implements PaymentService {
 @Override
 public String createPaymentQrcode() {
   return "支付宝支付二维码";
 }
}

@Service
@Profile({"default", "wechatpay"})
public class WechatpayService implements PaymentService {
 @Override
 public String createPaymentQrcode() {
   return "微信支付二维码";
 }
}

在 Spring Boot 中,默认的 profile 是 default,因此,PaymentService.createPaymentQrcode() -> 微信支付二维码。

你可以通过 spring.profiles.active 来激活某个特定 profile:


java -jar -Dspring.profiles.active='alipay' xxx.jar

PaymentService.createPaymentQrcode() -> 支付宝支付二维码。

多环境配置

在Spring Boot 中,多环境配置文件可以使用 application-{profile}.{properties|yml} 的方式。


@Component
@ConfigurationProperties("jdbc")
public class JdbcProperties {
 private String username;
 private String password;
 // getters and setters
}

开发环境 application-dev.properties 配置:


jdbc.username=root
jdbc.password=123654

生产环境 application-prod.properties 配置:


jdbc.username=produser
jdbc.password=16888888

或:

开发环境 application-dev.yml 配置:


jdbc:
username: root
password: 123654

生产环境 application-prod.yml 配置:


jdbc:
username: produser
password: 16888888

或:

只使用 application.yml,并在此文件中通过 --- 分隔符创建多 profile 配置:


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

命令行启动:


java -jar -Dspring.profiles.active=prod xxxx.jar

来源:http://fanlychie.github.io/post/spring-boot-profiles-usage.html?utm_source=tuicool&utm_medium=referral

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com