【SpringBoot】偏门

动态赋值

@Value

	@Value("${blog.id}")
    private Long id;

如果对象太多,一个一个绑定太麻烦。我们可以使用

@ConfigurationProperties(prefix = “blog”) //动态赋值的类
@EnableConfigurationProperties({Blog2.class}) //启动类
@PropertySource(“classpath:blog.properties”) //启动类

@Data
@Component
@ConfigurationProperties(prefix = "blog") //前缀为blog的
@PropertySource("classpath:blog.properties") //如果换了文件,用这个
public class Blog2 {
  private Long id;
  private String title;
  private String author;
}

多环境配置

需要满足 application-{profile}.properties 的格式,其中{profile}对应你的环境标识,比如:
dev——开发环境
test——测试环境
pre——灰度环境
prod——生产环境

想要使用对应的环境,只需要在application.properties中使用spring.profiles.active属性来设置。

例:
yaml:spring.profiles.active=test

命令行:java -jar 项目名称.jar --spring.profiles.active=dev

多数据源

datasource:
    master:
      jdbc-url:
      username:
      password:
      dirver:
    slave:
      jdbc-url:
      username:
      password:
      dirver:

这里通过 master 和 slave 对数据源进行了区分,但是加了 master 和 slave 之后,这里的配置就没法被 SpringBoot 自动加载了

此时需要我们手动的配置数据源

@Configuration
public class DataSourceConfiguration {

    @Primary
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource masterDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource slaveDataSource() {
        return DataSourceBuilder.create().build();
    }
}

再分别指定sqlSessionFactorysqlSessionTemplate。通过 @MapperScan 的属性指定

@Configuration
@MapperScan(
  basePackages = "com.fish.chapter7.master",
  sqlSessionFactoryRef = "masterSqlSessionFactory",
  sqlSessionTemplateRef = "masterSqlSessionTemplate")
public class MasterConfig {

  @Bean
  public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource) throws Exception {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(masterDataSource);
    return bean.getObject();
  }

  @Bean
  public SqlSessionTemplate masterSqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory masterSqlSessionFactory) throws Exception {
    return new SqlSessionTemplate(masterSqlSessionFactory);
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值