美文网首页
Spring Profile

Spring Profile

作者: 码中仙 | 来源:发表于2020-02-11 12:35 被阅读0次

Profile作用

用来解决不同环境下加载不同类、配置的一种方式。例如在项目环境和线上环境数据库配置不同,可用通过Profile机制来激活不同配置。
可以通过配置文件和注解两种方式来使用Profile。

使用Profile

注解方式

主要有以下两个注解:

  • @Profile - 标注一个特定环境
  • @ActiveProfile - 激活某个环境
public interface DataSource{
  String getName();
}

public DevDataSource implements DataSource{
  public String getName(){
    return "dev-ds";
  }
}

public ProductDataSource implements DataSource{
  public String getName(){
    return "product-ds";
  }
}

@Configuration
public class DataSourceConfiguration{
  @Bean
  @Profile("dev")
  public DataSource devDataSource(){
    return new DevDataSource();
  }

  @Bean
  @Profile("product")
  public DataSource productDataSource(){
    return new ProductDataSource();
  }
}

激活方式:
JVM参数:-Dspring.profiles.active=dev
标注:@ActiveProfile

配置文件方式

除了默认的 application.properties 文件外,还可以指定application-{profile}.properties的文件
通过JVM参数:-Dspring.profiles.active=dev 来加载相应的配置

相关文章

网友评论

      本文标题:Spring Profile

      本文链接:https://www.haomeiwen.com/subject/lnztfhtx.html