动态赋值
@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();
}
}
再分别指定sqlSessionFactory
和sqlSessionTemplate
。通过 @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);
}
}