通过实例了解Spring中@Profile的作用-创新互联

这篇文章主要介绍了通过实例了解Spring中@Profile的作用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

创新互联公司专注于企业成都全网营销推广、网站重做改版、额济纳网站定制设计、自适应品牌网站建设、H5开发商城建设、集团公司官网建设、外贸网站制作、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为额济纳等各大城市提供网站开发制作服务。

根据系统环境的不同,Profile可以用来切换数据源。例如切换开发,测试,生产环境的数据源。

举个例子:

先创建配置类MainProfileConfig:

@Configuration
@PropertySource("classpath:/jdbc.properties")
public class MainProfileConfig implements EmbeddedValueResolverAware {

  @Value("${db.user}")
  private String user;

  private String driverClass;

  private StringValueResolver stringValueResolver;

  @Profile("test")
  @Bean("testDataSource")
  public DataSource getTestDataSource(@Value("${db.password}") String pwd) throws PropertyVetoException {
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    comboPooledDataSource.setUser(user);
    comboPooledDataSource.setPassword(pwd);
    comboPooledDataSource.setDriverClass(driverClass);
    return comboPooledDataSource;
  }

  @Profile("dev")
  @Bean("devDataSource")
  public DataSource getDevDataSource(@Value("${db.password}") String pwd) throws PropertyVetoException {
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    comboPooledDataSource.setUser(user);
    comboPooledDataSource.setPassword(pwd);
    comboPooledDataSource.setDriverClass(driverClass);
    return comboPooledDataSource;
  }

  @Profile("pro")
  @Bean("proDataSource")
  public DataSource getproDataSource(@Value("${db.password}") String pwd) throws PropertyVetoException {
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    comboPooledDataSource.setUser(user);
    comboPooledDataSource.setPassword(pwd);
    comboPooledDataSource.setDriverClass(driverClass);
    return comboPooledDataSource;
  }

  @Override
  public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
    this.stringValueResolver = stringValueResolver;
    driverClass = stringValueResolver.resolveStringValue("${db.driverClass}");
  }
}

另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


分享标题:通过实例了解Spring中@Profile的作用-创新互联
网页地址:http://bzwzjz.com/article/ccssih.html

其他资讯

Copyright © 2007-2020 广东宝晨空调科技有限公司 All Rights Reserved 粤ICP备2022107769号
友情链接: 成都网站设计公司 成都网站设计 成都h5网站建设 盐亭网站设计 成都网站制作 自适应网站建设 成都网站建设 成都网站制作 成都网站建设公司 定制网站建设多少钱 成都网站建设 网站建设 成都网站制作 网站建设公司 网站建设推广 营销型网站建设 网站设计制作 网站建设公司 高端品牌网站建设 攀枝花网站设计 成都网站设计 网站制作报价