新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

通过实例了解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的作用-创新互联
URL标题:http://www.wjwzjz.com/article/ccssih.html
在线咨询
服务热线
服务热线:028-86922220
TOP