发布于 2017-08-19 02:33:35 | 272 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的精品教程,程序狗速度看过来!

Spring Boot

Spring Boot 项目旨在简化创建产品级的 Spring 应用和服务。你可通过它来选择不同的 Spring 平台。可创建独立的 Java 应用和 Web 应用,同时提供了命令行工具来允许 'spring scripts'.


本篇文章主要介绍了详解Spring Boot Profiles 配置和使用,具有一定的参考价值,有兴趣的可以了解一下

介绍

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHPERZ。



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务